/**
* TODO 维护最大堆
* @param arr
* @param i
* @param length
*/
private static void maxHeapify(int[] arr,int i,int length){
int leftIndex = 2*i+1;
int rightIndex = 2*(i+1);
int largestIndex = i;
if(leftIndex<length && arr[i]<arr[leftIndex]){
largestIndex = leftIndex;
}
if(rightIndex<length && arr[largestIndex]<arr[rightIndex]){
largestIndex = rightIndex;
}
if(largestIndex!=i){
swap(arr,i,largestIndex);
maxHeapify(arr,largestIndex,length);
}
}
/**
* TODO 交换两个数据的值
* @param arr
* @param i
* @param largestIndex
*/
private static void swap(int[] arr, int i, int largestIndex) {
int temp = arr[i];
arr[i] = arr[largestIndex];
arr[largestIndex] = temp;
}
/**
* TODO 建堆
* @param arr
*/
private static void buildMaxHeap(int[] arr){
for(int i=arr.length/2-1;i>=0;i--){
maxHeapify(arr,i,arr.length);
}
}
/**
* TODO 排序
* @param arr
*/
public static void heapSort(int[] arr){
buildMaxHeap(arr);
for(int i=arr.length-1;i>0;i--){
swap(arr,i,0);
maxHeapify(arr,0,i);
}
}
08-24
08-24
08-24