generated from alura/modelo-vitrinedev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquicksort.go
133 lines (100 loc) · 2.43 KB
/
quicksort.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
package sort
func QuickSort[T any](array []T, less func(T, T) bool) {
if len(array) <= 1 {
return
}
var mid int = positionPivotLomuto(array, less)
QuickSort(array[:mid], less)
if mid+1 < len(array) {
QuickSort(array[mid+1:], less)
}
}
func QuickSort3way[T any](array []T, less func(T, T) bool) {
if len(array) <= 1 {
return
}
var middle_start, middle_end int = positionPivot3way(array, less)
QuickSort(array[:middle_start], less)
if middle_end+1 < len(array) {
QuickSort(array[middle_end+1:], less)
}
}
func positionPivotLomuto[T any](array []T, less func(T, T) bool) int {
if len(array) <= 1 {
return 0
}
end := len(array) - 1
var greaterElemsIndex int = 0
for i := 0; i < end; i++ {
if !less(array[i], array[end]) {
continue
}
if i != greaterElemsIndex {
array[i], array[greaterElemsIndex] = array[greaterElemsIndex], array[i]
}
greaterElemsIndex++
}
if end != greaterElemsIndex {
array[end], array[greaterElemsIndex] = array[greaterElemsIndex], array[end]
}
return greaterElemsIndex
}
func positionPivotHoare[T any](array []T, less func(T, T) bool) int {
length := len(array)
if length <= 1 {
return 0
}
var pivot *T = &array[length-1]
var low, high int = 0, length - 2
for low < high {
if !less(array[low], *pivot) && less(array[high], *pivot) {
array[low], array[high] = array[high], array[low]
low++
high--
continue
}
if less(array[low], *pivot) {
low++
}
if !less(array[high], *pivot) {
high--
}
}
if less(array[low], *pivot) {
low++
}
array[length-1], array[low] = array[low], array[length-1]
return low
}
func positionPivot3way[T any](array []T, less func(T, T) bool) (int, int) {
if len(array) <= 1 {
return 0, 0
}
end := len(array) - 1
var greaterOrEqualIndex int = 0
for i := 0; i < end; i++ {
if !less(array[i], array[end]) {
continue
}
if i != greaterOrEqualIndex {
array[i], array[greaterOrEqualIndex] = array[greaterOrEqualIndex], array[i]
}
greaterOrEqualIndex++
}
var equalElemsIndex int = end - 1
for i := end - 1; i >= greaterOrEqualIndex; i-- {
// pivot >= array[i]
if !less(array[end], array[i]) {
continue
}
if i != equalElemsIndex {
array[i], array[equalElemsIndex] = array[equalElemsIndex], array[i]
}
equalElemsIndex--
}
equalElemsIndex++
if end != equalElemsIndex {
array[end], array[equalElemsIndex] = array[equalElemsIndex], array[end]
}
return greaterOrEqualIndex, equalElemsIndex
}