-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.go
58 lines (48 loc) · 955 Bytes
/
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
48
49
50
51
52
53
54
55
56
57
58
package main
import (
"fmt"
"math/rand"
"time"
)
func partition(arr []int, left, right int) int {
l, r := left, right
tmp := arr[l]
for l != r {
for l < r && arr[r] >= tmp {
r--
}
for l < r && arr[l] <= tmp {
l++
}
if l < r {
arr[l], arr[r] = arr[r], arr[l]
}
}
arr[l], arr[left] = arr[left], arr[l]
return l
}
func quickSort(arr []int, left, right int) {
if left > right {
return
}
pivot := partition(arr, left, right)
quickSort(arr, left, pivot - 1)
quickSort(arr, pivot + 1, right)
}
func main() {
total := 20
left := 1
right := 1000
arr := generateRandomArray(total, left, right)
fmt.Println("Origin array: ", arr)
quickSort(arr, 0, len(arr) - 1)
fmt.Println("Sorted array: ", arr)
}
func generateRandomArray(total, left, right int) []int {
arr := make([]int, total)
rand.Seed(time.Now().UnixNano())
for i := 0; i < total; i++ {
arr[i] = rand.Intn(right - left) + left
}
return arr
}