算法步骤
- 首先将待排序的数组构造成一个大根堆,此时,整个数组的最大值就是堆结构的顶端
- 将顶端的数与末尾的数交换,此时,末尾的数为最大值,剩余待排序数组个数为n-1
- 将剩余的n-1个数再构造成大根堆,再将顶端数与n-1位置的数交换,如此反复执行,便能得到有序数组
动图演示

代码
public static void heapSort(int[] arr) {
heapInsert(arr);
int size = arr.length;
while (size > 1) {
swap(arr, 0, size - 1);
size--;
heapify(arr, 0, size);
}
}
public static void heapInsert(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int currentIndex = i;
int fatherIndex = (currentIndex - 1) / 2;
while (arr[currentIndex] > arr[fatherIndex]) {
swap(arr, currentIndex, fatherIndex);
currentIndex = fatherIndex;
fatherIndex = (currentIndex - 1) / 2;
}
}
}
public static void heapify(int[] arr, int index, int size) {
int left = 2 * index + 1;
int right = 2 * index + 2;
while (left < size) {
int largestIndex;
if (arr[left] < arr[right] && right < size) {
largestIndex = right;
} else {
largestIndex = left;
}
if (arr[index] > arr[largestIndex]) {
largestIndex = index;
}
if (index == largestIndex) {
break;
}
swap(arr, largestIndex, index);
index = largestIndex;
left = 2 * index + 1;
right = 2 * index + 2;
}
}
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
参考:堆排序算法(图解详细流程)