public class SortHeap { public static void sort(int[] data) { // 构建大顶堆 for (int i = (data.length - 2) / 2; i >= 0; i--) { adjustHeap(data, i, data.length); } // 对顶元素与堆尾元素进行调整,重现调整堆为大顶堆 for (int j = data.length - 1; j >= 0; j--) { int temp = data[j]; data[j] = data[0]; data[0] = temp; adjustHeap(data, 0, j); } } public static void adjustHeap(int[] data, int i, int length) { int temp = data[i]; for (int k = i * 2 + 1; k < length; k = k * 2 + 1) { if (k + 1 < length && data[k] < data[k + 1]) { // 比较左孩子是否小于右孩子,如果小于,则直接比较右孩子 k++; } if (data[k] > temp) { data[i] = data[k]; i = k; } else { break; } } data[i] = temp; } public static void main(String[] args) { int data[] = {4, 5, 8, 1, 2, 3, 6, 7, 11, 10, 9}; for (int i = 0; i < data.length; i++) { System.out.print(data[i] + " "); } System.out.println(); System.out.println("-----------------------------"); sort(data); for (int i = 0; i < data.length; i++) { System.out.print(data[i] + " "); } System.out.println(); } }
输出如下: 4 5 8 1 2 3 6 7 11 10 9 ----------------------------- 1 2 3 4 5 6 7 8 9 10 11 Process finished with exit code 0