public class HeapSort {
public static void main(String[] args) {
int[] arr = {7, 6, 7, 11, 5, 12, 3, 0, 1};
System.out.println("之前:" + Arrays.toString(arr));
heapSort(arr);
System.out.println("升序:" + Arrays.toString(arr));
}
public static void heapSort(int[] arr) {
//构建大根堆
for (int i = 0; i < arr.length; i++) {
heapInsert(arr, i);
}
for (int j = arr.length - 1; j >= 0; j--) {
//每次把最大值放到数组尾部
swap(arr, 0, j);
//重新构建[0,j)区间的大根堆
adjustHeap(arr, 0, j);
}
}
private static void heapInsert(int[] arr, int idx) {
while (arr[idx] > arr[(idx - 1) / 2]) {
swap(arr, idx, (idx - 1) / 2);
idx = (idx - 1) / 2;
}
}
private static void adjustHeap(int[] arr, int idx, int len) {
for (int i = idx * 2 + 1; i < len; i = i * 2 + 1) {
//i指向idx子节点中较大的
if (i + 1 < len && arr[i] < arr[i + 1]) i++;
//若子节点大,子节点上浮
if (arr[i] > arr[idx]) {
swap(arr, i, idx);
idx = i;
} else break;
}
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
01-02