快速排序算法原理:
package main
import "fmt"
//[]int{1,2,3,4,5,6,7,8}
func qsort(ori []int) []int {
copy := append([]int{}, ori...)
var inner func(ori []int)
inner = func(ori []int) {
if len(ori) == 0 || len(ori) == 1 {
return
}
//找一个参考点最左边 元素个数>=2之后进行比较
ref := ori[0]
var i, j int
loopj := true
for i, j = 0, len(ori)-1; i != j; {
if loopj {
if ori[j] < ref {
ori[i] = ori[j]
i++ //该位置已经替换需要更新
loopj = false
} else {
j--
}
} else {
if ori[i] > ref {
ori[j] = ori[i]
j--
loopj = true
} else {
i++
}
}
}
ori[i] = ref
inner(ori[0:i])
//if i < len(ori) {
inner(ori[i+1:]) //equal ori[i+1:len(ori)]
// }
}
inner(copy)
return copy
}
/*
ori = []int{1, 4, 3, 2}
output = []int{1,2,3,4}
*/
func main() {
ori := []int{1, 4, 3, 2}
fmt.Println(qsort(ori))
}