-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathquicksort.go
77 lines (54 loc) · 979 Bytes
/
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
//
// The Algorithm Museum
// https://gcallah.github.io/algorithms/AlgorithmMuseum.html
//
// section: Quicksort
// author: rdodson
// created: Sun Feb 26 13:13:34 EST 2017
//
//
package main
import "fmt"
func quicksort(l []int, p int, r int) {
if p == -1 {
p = 0
}
if r == -1 {
r = len(l) - 1
}
if p < r {
var q = partition(l, p, r)
quicksort(l, p, q-1)
quicksort(l, q+1, r)
}
}
func partition(l []int, p int, r int) int {
var x int = l[r]
var i int = p - 1
for j := p; j < r; j++ {
if l[j] <= x {
i += 1
swap(l, i, j)
}
}
swap(l, i+1, r)
return i + 1
}
func swap(l []int, i int, j int) {
var temp int = l[i]
l[i] = l[j]
l[j] = temp
}
func printarray(name string, l []int) {
fmt.Printf("%s: ", name)
for i := 0; i < len(l); i++ {
fmt.Printf("%d ", l[i])
}
fmt.Printf("\n")
}
func main() {
var l = []int{9, 7, 8, 5, 2, 6, 3, 1, 4, 0}
printarray(" unsorted", l)
quicksort(l, -1, -1)
printarray("quicksort", l)
}