排序算法

常考排序

快速排序

func QuickSort(nums []int) []int {
    // 思路:把一个数组分为左右两段,左段小于右段
    quickSort(nums, 0, len(nums)-1)
    return nums

}
// 原地交换,所以传入交换索引
func quickSort(nums []int, start, end int) {
    if start < end {
        // 分治法:divide
        pivot := partition(nums, start, end)
        quickSort(nums, 0, pivot-1)
        quickSort(nums, pivot+1, end)
    }
}
// 分区
func partition(nums []int, start, end int) int {
    // 选取最后一个元素作为基准pivot
    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
}

归并排序

堆排序

用数组表示的完美二叉树 complete binary tree

完美二叉树 VS 其他二叉树

image.png

动画展示

image.png

核心代码

参考

十大经典排序

二叉堆

练习

最后更新于

这有帮助吗?