//快速排序
func QuickSort(s []int) {
sort(s, 0, len(s)-1)
}
func sort(s []int, lo, hi int) {
if lo >= hi {
return
}
k := partition(s, lo, hi)
sort(s, lo, k)
sort(s, k+1, hi)
}
func partition(s []int, lo, hi int) int {
i, j := lo, hi+1 //将lo作为中间值
for {
for {
i++
if i == hi || s[i] > s[lo] {
break
}
}
for {
j--
if j == lo || s[j] <= s[lo] {
break
}
}
if i >= j {
break
}
swap(s, i, j)
}
swap(s, lo, j)
return j
}
func swap(s []int, i int, j int) {
s[i], s[j] = s[j], s[i]
}
测试:
s := []int{9, 0, 6, 5, 8, 2, 1, 7, 4, 3}
fmt.Println(s)
QuickSort(s)
fmt.Println(s)
输出:
[9 0 6 5 8 2 1 7 4 3]
[0 1 2 3 4 5 6 7 8 9]
泛型版本
type SliceConstraint interface {
~int | ~int8 | ~int64 | ~int32 | ~float64 | ~float32
}
// 定义任意类型的切片
func QuickSort[T SliceConstraint](slice []T) []T {
if len(slice) <= 1 {
return slice
}
pivot := slice[len(slice)-1] // 选择最后一个元素作为轴心
left := []T{}
right := []T{}
for _, v := range slice[:len(slice)-1] {
if v < pivot {
left = append(left, v)
} else {
right = append(right, v)
}
}
return append(QuickSort(left), append([]T{pivot}, QuickSort(right)...)...)
}