在数据规模不是很大的情况下效率很高,一个简单又经典的算法。
理解了思想不论用什么语言实现起来都是很容易的,下面是用 golang 描述的快速排序算法
package main import ( "fmt" ) func main() { var num = []int{3, 2, 4, 6, 5, 1} num = IntQSort(num, true) fmt.Println(num) } func IntQSort(n []int, order bool) []int { ls := make([]int, len(n)) for i := range n { ls[i] = n[i] } return IntQuickSort(ls, order) } /* 快速排序算法 * ls 排序码数组 * order true 表示升序,false 表示降序 */ func IntQuickSort(ls []int, order bool) []int { tmp := ls[0] left, i := 0, 0 right, j := len(ls)-1, len(ls)-1 d := 1 if left < right { for i < j { if order == true { if d == 1 { if tmp > ls[j] { ls[i] = ls[j] i += 1 d = -1 } else { j -= 1 d = 1 } } else { if tmp < ls[i] { ls[j] = ls[i] j -= 1 d = 1 } else { i += 1 d = -1 } } if i == j { ls[i] = tmp } } else { if d == 1 { if tmp < ls[j] { ls[i] = ls[j] i += 1 d = -1 } else { j -= 1 d = 1 } } else { if tmp > ls[i] { ls[j] = ls[i] j -= 1 d = 1 } else { i += 1 d = -1 } } if i == j { ls[i] = tmp } } } if i == right { IntQuickSort(ls[left:i], order) } else if i == 0 { IntQuickSort(ls[i+1:right+1], order) } else { IntQuickSort(ls[left:i], order) IntQuickSort(ls[i+1:right+1], order) } } return ls }