![[img/elementary-sort.png]]
常考排序
快速排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| func QuickSort(nums []int) []int { quickSort(nums, 0, len(nums)-1) return nums
}
func quickSort(nums []int, start, end int) { if start < end { pivot := partition(nums, start, end) quickSort(nums, 0, pivot-1) quickSort(nums, pivot+1, end) } }
func partition(nums []int, start, end int) int { p := nums[end] i := start for j := start; j < end; j++ { if nums[j] < p { swap(nums, i, j) i++ } } swap(nums, i, end) return i }
func swap(nums []int, i, j int) { t := nums[i] nums[i] = nums[j] nums[j] = t }
|
归并排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| func MergeSort(nums []int) []int { return mergeSort(nums) } func mergeSort(nums []int) []int { if len(nums) <= 1 { return nums } mid := len(nums) / 2 left := mergeSort(nums[:mid]) right := mergeSort(nums[mid:]) result := merge(left, right) return result } func merge(left, right []int) (result []int) { l := 0 r := 0 for l < len(left) && r < len(right) { if left[l] > right[r] { result = append(result, right[r]) r++ } else { result = append(result, left[l]) l++ } } result = append(result, left[l:]...) result = append(result, right[r:]...) return }
|
堆排序
用数组表示的完美二叉树 complete binary tree
完美二叉树 VS 其他二叉树
核心代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| package main
func HeapSort(a []int) []int { for i := len(a)/2 - 1; i >= 0; i-- { sink(a, i, len(a)) } for i := len(a) - 1; i >= 1; i-- { swap(a, 0, i) sink(a, 0, i) } return a } func sink(a []int, i int, length int) { for { l := i*2 + 1 r := i*2 + 2 idx := i if l < length && a[l] > a[idx] { idx = l } if r < length && a[r] > a[idx] { idx = r } if idx == i { break } swap(a, i, idx) i = idx } } func swap(a []int, i, j int) { a[i], a[j] = a[j], a[i] }
|