下面是一个 Golang 对切片的快速排序的例子,排序的对象是slice int 类型。
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
package main
import (
"fmt"
)
func QSort(arr []int, start int, end int) {
var (
key int = arr[start]
low int = start
high int = end
)
for {
for low < high {
if arr[high] < key {
arr[low] = arr[high]
break
}
high--
}
for low < high {
if arr[low] > key {
arr[high] = arr[low]
break
}
low++
}
if low >= high {
arr[low] = key
break
}
}
if low-1 > start {
QSort(arr, start, low-1)
}
if high+1 < end {
QSort(arr, high+1, end)
}
}
func main() {
arr := []int{5, 1, 3, 0, 9, 8, 7, 4, 6}
fmt.Println(arr)
QSort(arr, 0, len(arr)-1)
fmt.Println(arr)
}
输出:
1
2
[5 1 3 0 9 8 7 4 6]
[0 1 3 4 5 6 7 8 9]
本文网址: https://golangnote.com/topic/32.html 转摘请注明来源