You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
package main
|
|
|
|
|
|
|
|
// 快速排序
|
|
|
|
func main() {
|
|
|
|
var a = []int{29, 10, 14, 37, 25, 18, 30} // 创建数组的简写声明
|
|
|
|
Quick(a, 0, len(a)-1)
|
|
|
|
|
|
|
|
for _, i2 := range a {
|
|
|
|
print(i2, "\t") // 输出每一个值
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
Quick 实现快速排序 O(n * log(n))
|
|
|
|
a : 被排序数组
|
|
|
|
返回:排序完毕数组
|
|
|
|
*/
|
|
|
|
func Quick(slice []int, left, right int) {
|
|
|
|
if left < right {
|
|
|
|
mid := partition(slice, left, right) // 获取归位中值
|
|
|
|
Quick(slice, left, mid-1) // 操作 中值 左边数组
|
|
|
|
Quick(slice, mid+1, right) // 操作 中值 右边数组
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
partition 归位函数,获取一个关于某值对称的数组
|
|
|
|
*/
|
|
|
|
func partition(slice []int, left, right int) int {
|
|
|
|
tmp := slice[left] // 获取左侧第一个数
|
|
|
|
for left < right {
|
|
|
|
// 进行逐个实现归位操作,将列表形成一个对称列表
|
|
|
|
// 左边比 tmp 大的数,调至右边
|
|
|
|
for left < right && slice[right] >= tmp {
|
|
|
|
right--
|
|
|
|
}
|
|
|
|
slice[left] = slice[right]
|
|
|
|
|
|
|
|
// 右边比 tmp 小的数,调至左边
|
|
|
|
for left < right && slice[left] <= tmp {
|
|
|
|
left++
|
|
|
|
}
|
|
|
|
slice[right] = slice[left]
|
|
|
|
}
|
|
|
|
slice[left] = tmp
|
|
|
|
return left
|
|
|
|
}
|