代码
public class Sort {
public static void main(String[] args) {
int[] arr = {1, 4, 6, 2, 3, 4};
heapSort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.print(i + " ");
}
}
public static void heapDown(int[] array, int parent, int length) {
int temp = array[parent];
int child = 2 * parent + 1;
while (child < length) {
if (child + 1 < length && array[child] < array[child + 1]) child++;
if (temp >= array[child]) break;
array[parent] = array[child];
parent = child;
child = 2 * child + 1;
}
array[parent] = temp;
}
public static void heapSort(int[] list) {
for (int i = list.length / 2; i >= 0; i--) {
heapDown(list, i, list.length - 1);
}
for (int i = list.length - 1; i > 0; i--) {
int temp = list[i];
list[i] = list[0];
list[0] = temp;
heapDown(list, 0, i);
}
}
}
这篇主要自己看的,懒得写注释分析了。其实这种经典数据结构是不好写代码注释的,原理如果你只是懂个皮毛,代码就不用看了,否则就是一种煎熬啊