-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsorting.go
134 lines (116 loc) · 2.11 KB
/
sorting.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package main
import (
"fmt"
"math/rand"
"time"
)
func selectionSort(arr []int) {
n := len(arr)
for i := 0; i < n; i++ {
min := i
for j := i; j < n; j++ {
if arr[j] < arr[i] {
min = j
}
}
if min != i {
arr[i], arr[min] = arr[min], arr[i]
}
}
}
func bubbleSort(arr []int) {
n := len(arr)
for i := 0; i < n-1; i++ {
swap := false
for j := 0; j < n-i-1; j++ {
if arr[j] > arr[j+1] {
arr[j], arr[j+1] = arr[j+1], arr[j]
swap = true
}
}
if !swap {
break
}
}
}
func insertionSort(arr []int) {
n := len(arr)
for i := 1; i < n; i++ {
j := i - 1
key := arr[i]
for j >= 0 && arr[j] > key {
arr[j+1] = arr[j]
j--
}
arr[j+1] = key
}
}
func mergeSort(arr []int) []int {
n := len(arr)
if n <= 1 {
return arr
}
mid := n / 2
l := mergeSort(arr[:mid])
r := mergeSort(arr[mid:])
i, j := 0, 0
final := []int{}
for i < len(l) && j < len(l) {
if l[i] < r[j] {
final = append(final, l[i])
i++
} else {
final = append(final, r[j])
j++
}
}
for ; i < len(l); i++ {
final = append(final, l[i])
}
for ; j < len(r); j++ {
final = append(final, r[j])
}
return final
}
func main() {
rand.Seed(time.Now().Unix())
arr := rand.Perm(10000)
start := time.Now()
selectionSort(arr)
fmt.Printf(" selectionSort took at time %v\n", time.Since(start))
arr=nil
arr = rand.Perm(10000)
start = time.Now()
bubbleSort(arr)
fmt.Printf(" bubbleSort took at time %v\n", time.Since(start))
arr=nil
arr = rand.Perm(10000)
start = time.Now()
insertionSort(arr)
fmt.Printf(" insertionSort took at time %v\n", time.Since(start))
arr=nil
arr = rand.Perm(10000)
start = time.Now()
quickSort(arr, 0, len(arr)-1)
fmt.Printf(" quickSort took at time %v\n", time.Since(start))
}
func partition(arr []int, low, high int) int {
key := arr[high]
j := low
for i := low; i < high; i++ {
if arr[i] < key {
arr[i], arr[j] = arr[j], arr[i]
j++
}
}
arr[j], arr[high] = arr[high], arr[j]
return j
}
func quickSort(arr []int, low, high int) {
if low >= high {
return
}
p := partition(arr, low, high)
quickSort(arr, low, p-1)
quickSort(arr, p+1, high)
}