排序算法
- 快速排序
任意选取一个基准数据,把大于基准和小于基准的数据分列两边;然后再分别对大于基准的数列和小于基准的数列进行递归操作,直至数组有序
以下是golang的实现,仅供参考
package main
import "fmt"
func main() {
var lists = [][]int{
[]int{2, 4, 1, 7, 5, 9},
[]int{9, 6, 8, 2, 1, 6, 2, 0, 111, 3, 3, 3, 5, 6, 7, 9, 1, 2, 9, 7, 6},
[]int{1},
[]int{2, 4},
nil,
}
for _, list := range lists {
l5 := quickSort(list)
fmt.Println(l5)
}
}
// quickSort 快速排序
func quickSort(l []int) []int {
length := len(l)
if length <= 1 {
return l
}
qSort(l, 0, length-1)
return l
}
func qSort(l []int, L, R int) {
if L < R {
partitionIndex := partition(l, L, R)
qSort(l, L, partitionIndex-1)
qSort(l, partitionIndex+1, R)
}
}
func partition(l []int, L, R int) int {
var pivot = L
var index = pivot + 1
for i := index; i <= R; i++ {
if l[i] < l[pivot] {
l[i], l[index] = l[index], l[i]
index++
}
}
l[pivot], l[index-1] = l[index-1], l[pivot]
return index - 1
}
执行输出如下
[1 2 4 5 7 9]
[0 1 1 2 2 2 3 3 3 5 6 6 6 6 7 7 8 9 9 9 111]
[1]
[2 4]
[]