堆排序详细解说

思路分析

堆排序的过程如下:
由于利用小堆会占用额外空间,因此先将一个堆按照大堆的方式进行创建,然后取堆顶元素与堆中的最后一个元素进行交换,接着将最后一个元素出堆,将剩余的元素进行向下调整,重新调整成一个大堆,接着再重复以上操作,知道排序完成。

注意:排升序要建大堆;排降序要建小堆

图解

在这里插入图片描述

代码实现

    public static void heapSort(int[] array){
        creatHeap(array);
        for (int i = 0; i < array.length-1; i++){
            exchange(array,0,array.length - 1 -i);

            shiftDown(array, array.length -1 -i, 0);

        }
    }
    public static void shiftDown(int[] array, int size, int index){
        //向下调整  大堆!!!!!
        int parent = index;
        int child = 2*parent + 1;
        while (child < size){
            if (child + 1 < size && array[child+1] > array[child]){
                child = child+1;
            }
            if (array[child] > array[parent]){
                exchange(array,child,parent);
            }else {
                break;
            }
            parent = child;
            child = 2 * parent + 1;
        }
    }

    private static void creatHeap(int[] array) {
        for (int i = (array.length - 1 - 1)/2; i >= 0; i--){
            shiftDown(array,array.length,i);
        }
    }


    private static void exchange(int[] array, int bound, int cur) {
        int tmp = array[bound];
        array[bound] = array[cur];
        array[cur] = tmp;
    }

性能分析

时间复杂度:
O(N*log(N))

空间复杂度:
O(1)

稳定性:
不稳定排序

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值