堆排序已經忘記的差很少了,藉此回顧一下。詳見百度百科
java
public class HeapSort { //待排序數組,第0個元素無效 private static int[] array = {-1, 3, 1, 5, 10, 7, 8, 4}; //數組的有效元素個數 private static int size = array.length - 1; //交換數組的第i和第j個元素 private void swap(int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } //遞歸調整堆 private void heapAdjust(int index, int heapSize) { int leftChildIndex = index * 2; int rightChildIndex = index * 2 + 1; int tempIndex = index; if (index <= heapSize / 2) { //大頂堆 if (leftChildIndex <= heapSize && array[leftChildIndex] >= array[tempIndex]) { tempIndex = leftChildIndex; } if (rightChildIndex <= heapSize && array[rightChildIndex] >= array[tempIndex]) { tempIndex = rightChildIndex; } if (tempIndex != index) { swap(tempIndex, index); heapAdjust(tempIndex, heapSize); //遞歸調用 } } } //建立堆 private void buildHeap() { for (int i = size / 2 ; i >= 1 ; i--) { heapAdjust(i, size); } System.out.println("初始大頂堆:"); for (int i : array) { if (i == -1) { continue; //-1爲無效值 } System.out.print(" " + i); } } //堆排序 public void heapSort() { buildHeap(); //首先建立大頂堆 for (int i = size ; i >= 1 ; i--) { swap(1, i); heapAdjust(1, i - 1); } System.out.println("完成排序:"); for (int i : array) { if (i == -1) { continue; //-1爲無效值 } System.out.print(" " + i); } } }