-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquicksort.go
80 lines (69 loc) · 1.57 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
package Hal
/*
QuickSort sorts an array using Iterative Quick Sort algorithm.
Quick Sort works pretty well on large slice
*/
func QuickSort(a []int, scheme string) {
lo := 0
hi := len(a) - 1
quickSortRecur(a, lo, hi, scheme)
return
}
// quickSortRecur sorts the array iteratively
func quickSortRecur(a []int, lo, hi int, scheme string) {
if lo < hi {
var pos int
if scheme == "hoare" {
pos = hoare(a, lo, hi)
quickSortRecur(a, lo, pos, scheme)
quickSortRecur(a, pos + 1, hi, scheme)
} else {
pos = lomuto(a, lo, hi)
quickSortRecur(a, lo, pos - 1, scheme)
quickSortRecur(a, pos + 1, hi, scheme)
}
}
}
/*
lomuto partition does three things:
- takes last element as pivot and places the pivot at its correct place
- make all the numbers to the left of the pivot smaller than it
- make all the numbers to the right of the pivot larger than it
*/
func lomuto(a []int, lo, hi int) int {
pivot := a[hi]
i := lo
for j := lo; j < hi; j ++ {
if a[j] < pivot {
a[i], a[j] = a[j], a[i]
i ++
}
}
a[i], a[hi] = a[hi], a[i]
return i
}
/*
hoare partition is similar to lomuto except that:
- takes medium as the pivot and places the pivot at its correct place
- moving check points from both lo->mid and hi->mid
- theoretically hoare should be more efficient than lomuto as it has less swaps
*/
func hoare(a []int, lo, hi int) int {
pivot := a[lo + ((hi - lo) / 2)]
i := lo - 1
j := hi + 1
for {
i = i + 1
for a[i] < pivot {
i = i + 1
}
j = j - 1
for a[j] > pivot {
j = j - 1
}
if i >= j {
return j
}
a[i], a[j] = a[j], a[i]
}
}