-
Notifications
You must be signed in to change notification settings - Fork 1
/
sort.go
71 lines (65 loc) · 1.34 KB
/
sort.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
package slices
func partition[T Ordered](s []T, low, high int) int {
for j := low; j < high; j++ {
if s[j] < s[high] {
s[low], s[j] = s[j], s[low]
low++
}
}
s[low], s[high] = s[high], s[low]
return low
}
func quickSort[T Ordered](s []T, low, high int) {
if low < high {
if high-low < 12 {
insertionSort(s, low, high)
} else {
p := partition(s, low, high)
quickSort(s, low, p-1)
quickSort(s, p+1, high)
}
}
}
func insertionSort[T Ordered](s []T, a, b int) {
for i := 1; i < b-a+1; i++ {
j := i
for j > 0 {
if s[a+j] < s[a+j-1] {
s[a+j-1], s[a+j] = s[a+j], s[a+j-1]
}
j--
}
}
}
func partitionFunc[T any](s []T, low, high int, less func(T, T) bool) int {
for j := low; j < high; j++ {
if less(s[j], s[high]) {
s[low], s[j] = s[j], s[low]
low++
}
}
s[low], s[high] = s[high], s[low]
return low
}
func quickSortFunc[T any](s []T, low, high int, less func(T, T) bool) {
if low < high {
if high-low < 12 {
insertionSortFunc(s, low, high, less)
} else {
p := partitionFunc(s, low, high, less)
quickSortFunc(s, low, p-1, less)
quickSortFunc(s, p+1, high, less)
}
}
}
func insertionSortFunc[T any](s []T, a, b int, less func(T, T) bool) {
for i := 1; i < b-a+1; i++ {
j := i
for j > 0 {
if less(s[a+j], s[a+j-1]) {
s[a+j-1], s[a+j] = s[a+j], s[a+j-1]
}
j--
}
}
}