public static void createHeap(int[] arry){
for(int i = (arry.length-1-1)/2; i>=0 ;i--){
adjustDown(arry,i,arry.length);
}
}
private static void adjustDown(int[] arry, int root, int length) {
int parent = root;
int child = 2*parent+1;
while(child < length){
if(child+1 <length && arry[child] < arry[child +1]){
child++;
}
if(arry[child] > parent){
int tmp = arry[child];
arry[child] = arry[parent];
arry[parent] = tmp;
parent = child;
child = 2*parent + 1;
}else{
break;
}
}
}
public static void heapSort(int[] arry){
createHeap(arry);
int end = arry.length-1;
while(end > 0){
int tmp = arry[0];
arry[0] = arry[end];
arry[end] = tmp;
adjustDown(arry,0,end);
end--;
}
}
public static void main(String[] args) {
int[] arry = {12,5,9,34,6,8,33,56,89,0,7,4,22,55,7};
System.out.println(Arrays.toString(arry));
heapSort(arry);
System.out.println(Arrays.toString(arry));
}
转载请注明原文地址:https://blackberry.8miu.com/read-27395.html