-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquicksort.go
More file actions
39 lines (35 loc) · 821 Bytes
/
quicksort.go
File metadata and controls
39 lines (35 loc) · 821 Bytes
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
package sorting
import (
"math/rand"
)
func get_random_pivot(right int) int {
if right < 1 {
return right
}
pivot := rand.Int() % right
return pivot
}
func quicksort(s []int32) {
if len(s) > 1 {
pivot := get_random_pivot(len(s))
normalized_index := partition(s, pivot)
quicksort(s[:normalized_index])
quicksort(s[normalized_index+1:])
} else {
return
}
}
func partition(s []int32, index int) int {
sentinel := s[index]
max_index := len(s) - 1
s[index], s[max_index] = s[max_index], s[index]
stored := 0
for i:=0;i<max_index;i++ {
if s[i] < sentinel {
s[i], s[stored] = s[stored], s[i]
stored++
}
}
s[stored], s[max_index] = s[max_index], s[stored]
return stored
}