前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >堆排序详细解说

堆排序详细解说

作者头像
小雨的分享社区
发布2022-10-26 15:05:35
1770
发布2022-10-26 15:05:35
举报
文章被收录于专栏:小雨的CSDN

思路分析

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

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

图解

代码实现

代码语言:javascript
复制
    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)

稳定性: 不稳定排序

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-02-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 思路分析
  • 图解
  • 代码实现
  • 性能分析
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档