package 排序;
import common.Utils;
public class HeapSort {
public static void Adjust(int[] arr,int startIndex,int len){
int childIndex = 0;
int threshold = len-1;
for(;2*startIndex+1<len;startIndex = childIndex){
childIndex = 2*startIndex+1;
//if childIndex = len-1,then arr[childIndex+1] = arr[len],
//which is ArrayIndexOutofBoundsException
if(childIndex<threshold && arr[childIndex]<arr[childIndex+1])
childIndex++;
if(arr[childIndex]>arr[startIndex]){
Utils.swap(arr, startIndex, childIndex);
}else {
break;
}
}
}
public static void heapSort(int[] arr){
long start = System.nanoTime();
int midIndex = arr.length/2-1;
//初始化堆
for(int i = midIndex;i>=0;i--){
Adjust(arr, i, arr.length);
}
//调整堆
for(int i=arr.length-1;i>=1;i--){
Utils.swap(arr, 0, i);
Adjust(arr, 0, i);
}
long end = System.nanoTime();
System.out.println("runtime:"+(end-start)/1e6);
}
public static void main(String[] args) {
int[] arr = Utils.produceNum(0, 1000000, 600000);
System.out.println("before heapSort");
//Utils.displayByOneLine(arr);
heapSort(arr);
System.out.println("after heapSort");
//Utils.displayByOneLine(arr);
}
}