快速排序
func quickSort(arr []int) {
n := len(arr)
if n < 2 { return arr }
l, r := 0, n-1
privot := arr[l]
for l < r {
for r > l && arr[r] >= privot { r-- }
arr[l] = arr[r]
for l < r && arr[l] <= privot { l++ }
arr[r] = arr[l]
}
arr[l] = privot
MySort(arr[:l]) // 排左半部分
MySort(arr[l+1:]) // 排右半部分
return arr
}
归并排序
分析可见:[算法详解][归并排序]Merge sort
题目:力扣315. 计算右侧小于当前元素的个数
type pair struct {
idx, val int
}
func countSmaller(nums []int) []int {
n := len(nums)
counts := make([]int, n)
tnums := make([]pair, n)
temps := make([]pair, n)
for i:=0; i<n; i++ {
tnums[i] = pair{idx:i, val:nums[i]}
}
var mergeSort func(left, right int)
mergeSort = func(left, right int) {
if left >= right { return }
mid := (left + right) >> 1
mergeSort(left, mid)
mergeSort(mid+1, right)
l, r, k := left, mid+1, left
for ; l<=mid && r<=right; k++ {
if tnums[l].val <= tnums[r].val {
temps[k] = tnums[l]
counts[tnums[l].idx] += r - (mid + 1)
l++
} else {
temps[k] = tnums[r]
r++
}
}
for ; l <= mid; l, k = l+1, k+1 {
temps[k] = tnums[l]
counts[tnums[l].idx] += r - (mid + 1)
}
for ; r <= right; r, k = r+1, k+1 {
temps[k] = tnums[r]
}
for k=left; k<= right; k++ { tnums[k] = temps[k] }
}
mergeSort(0, n-1)
return counts
}
堆排序
import (
"container/heap"
)
type IntHeap []int
func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) { *h = append(*h, x.(int)) }
func (h *IntHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[:n-1]
return x
}
func GetLeastNumbers_Solution( input []int , k int ) []int {
if k<1 || k>len(input) { return []int{} }
// 初始化堆
hp := &IntHeap{}
heap.Init(hp)
// 依次加入元素
for i := 0; i < len(input); i++ {
heap.Push(hp, input[i]) // 元素入堆
if len(*hp)>k { heap.Pop(hp) } // 将队中最大的元素出堆
}
return *hp // 返回堆中剩余的元素
}