堆排序算法分析 和代码实现

package algorithm;

public class Heap {
//堆的性质
//(1)一个含有n个元素的堆,高度floor(lgn).
//(2)对于任何一个含有n 元素的堆中,至多有celling(n/(2^(h+1)))个高度为h的节点(可用数学归纳法)
//堆排序 需要注意的点
//(1)通过 max_heapify中heapSize参数来控制堆化的数量。
//(2)数组下标0 开始 注意月结的问题。
//(3)对一个数组堆化,heapsize 始终是数组的大小。
//堆这种数据结构,其实就是完全二叉树。时间复杂度O(nlgn).值得注意的是 函数max_heapify()时间复杂度O(h),h=floor(lgn)
//函数build_max_heap ()的时间复杂度O(n),也就是我们可以在线性时间内构造最大堆。z这里你就可以知道为什么是堆排序算法时间复杂度为nlgn了。
//
//学到的题外技巧,选中一段代码,按住TAB键使其右一一段你想要的距离 来调节整体效果

        public static void max_heapify(int[] A,int i,int heapSize){
            int l=2*i+1;
            int r=2*i+2;
             int max=i;

             if(l<heapSize&&A[l]>A[max]){
                 max=l;
             }
             if(r<heapSize&&A[r]>A[max]){
                 max=r;
             }

             if(max!=i){
                 ArrayUtils.exchangeElement(A, max, i);

                 max_heapify(A, max,heapSize);
             }
        }
        public static void build_max_heap(int[] A){
            for(int i=(A.length-2)/2;i>=0;i--){
                max_heapify(A, i,A.length);
            }

        }
        public static void heapSort(int[] A){
            build_max_heap(A);
            //ArrayUtils.exchangeElement(A, A.length, 0);
            for(int i=A.length-1;i>=0;i--){
                ArrayUtils.exchangeElement(A, i, 0);
                max_heapify(A, 0,i);
            }

        }
        public static void main(String[] args) {
            int[] arr={212,2,23,1,2,3,423,4,24,123,13,132,331};
            heapSort(arr);
            ArrayUtils.printArray(arr);
        }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值