-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
47 lines (41 loc) · 1.07 KB
/
main.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
package main
import "fmt"
func main() {
arr := []int{9, 1, 8, 2, 7, 3, 6, 4, 5}
fmt.Println(quickSort(arr))
}
func quickSort(array []int) []int {
quickSortHelper(array, 0, len(array)-1)
return array
}
func quickSortHelper(array []int, startIndex, endIndex int) []int {
if startIndex >= endIndex {
return array
}
pivotIndex := startIndex
leftIndex := startIndex + 1
rightIndex := endIndex
for rightIndex >= leftIndex {
if array[leftIndex] > array[pivotIndex] && array[rightIndex] < array[pivotIndex] {
swap(leftIndex, rightIndex, array)
}
if array[leftIndex] <= array[pivotIndex] {
leftIndex++
}
if array[rightIndex] >= array[pivotIndex] {
rightIndex--
}
}
swap(pivotIndex, rightIndex, array)
if rightIndex-1-startIndex < endIndex-(rightIndex-1) {
quickSortHelper(array, startIndex, rightIndex-1)
quickSortHelper(array, rightIndex+1, endIndex)
} else {
quickSortHelper(array, rightIndex+1, endIndex)
quickSortHelper(array, startIndex, rightIndex-1)
}
return array
}
func swap(i, j int, array []int) {
array[i], array[j] = array[j], array[i]
}