public class Main {
public static void main(String[] args) {
int[] arr = {0, 2, 1, 5, 8, 2, 4, 3, 7, 6, 5};
heapSort(arr, arr.length - 1);
for(int i = 1; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
public static void heapSort(int[] arr, int size) {
initHeap(arr, size);
for(int i = size; i >= 1; i--) {
int temp = arr[1];
arr[1] = arr[i];
arr[i] = temp;
adjustHeap(arr, i - 1, 1);
}
}
public static void initHeap(int[] arr, int size) {
int i;
for(i = size / 2; i >= 1; i--) {
adjustHeap(arr, size, i);
}
}
public static void adjustHeap(int[] arr, int size, int i) {
int lchild = 2 * i;
int rchild = 2 * i + 1;
int max = i;
if(i <= size / 2) {
if(lchild <= size && arr[lchild] > arr[max]) {
max = lchild;
}
if(rchild <= size && arr[rchild] > arr[max]) {
max = rchild;
}
if(max != i) {
int temp = arr[i];
arr[i] = arr[max];
arr[max] = temp;
adjustHeap(arr, size, max);
}
}
}
}
1、构建初始大根堆很重要
2、索引从1开始
3、if(i <= size/2)!!!