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);
}
}