import java.util.Arrays;
public class HeapSort {
//数组arr下标为0的位置不使用,待排序数字放入下标为 1 ~ arr.length-1 的位置,并对这些位置上的元素排序
public static void sort(int arr[]) {
HeapSort hs = new HeapSort();
hs.buildMaxHeap(arr, 1, arr.length - 1);
System.out.println("buildMaxHeap result : " + Arrays.toString(arr));
hs.adjustHeap(arr, 1, arr.length - 1);
}
//建最大堆
public void buildMaxHeap(int[] arr, int start, int end) {
for (int i = end ; i >= start; i--) {
downWithCycle(arr, i, end);
}
}
//堆调整
public void adjustHeap(int[] arr, int start, int end) {
for (int i = end; i > start; i--) {
swap(arr, start, i);
System.out.println("swap result : " + Arrays.toString(arr));
downWithCycle(arr, start, i - 1);
}
}
//下滤
public void downWithCycle(int[] arr, int start, int end) {
if (start >= end) {
return;
}
int index = start;
int leftIndex = 2 * index;
int rightIndex = 2 * index + 1;
while (leftIndex <= end) {
int biggestIndex = index;
if(arr[leftIndex]>arr[biggestIndex]){
biggestIndex = leftIndex;
}
if ((rightIndex <= end) && (arr[rightIndex] > arr[biggestIndex])) {
biggestIndex = rightIndex;
}
if(biggestIndex != index){
swap(arr,index,biggestIndex);
index = biggestIndex;
leftIndex = 2 * index;
rightIndex = 2 * index + 1;
}else{
return ;
}
}
}
//交换下标为a和b的元素
private void swap(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
public static void main(String[] args) {
int[] arr = { 0, 11, 2, 31, 444, 52, 16, 71, 8, 93, 10 };
System.out.println("origin : " + Arrays.toString(arr));
HeapSort.sort(arr);
System.out.println("result : " + Arrays.toString(arr));
}
}