堆排序(Heapsort)是一种利用数据结构中的堆进行排序的算法,分为构建初始堆,减小堆的元素个数,调整堆共3步。
(一)算法实现
1 protected void sort(int[] toSort) { 2 buildHeap(toSort); 3 for (int i = toSort.length - 1; i > 0; i--) { 4 CommonUtils.swap(toSort, 0, i); 5 adjustHeap(toSort, 0, i); 6 } 7 } 8 9 /** 10 * 11 * @param toSort 12 * array of heap, begins from 0 13 * @param index 14 * index to adjust 15 * @param size 16 * size of heap 17 */ 18 private void adjustHeap(int[] toSort, int index, int size) { 19 int leftNode = index * 2 + 1; 20 int rightNode = leftNode + 1; 21 22 int maxIndex = index; 23 if (leftNode < size && toSort[leftNode] > toSort[maxIndex]) { 24 maxIndex = leftNode; 25 } 26 if (rightNode < size && toSort[rightNode] > toSort[maxIndex]) { 27 maxIndex = rightNode; 28 } 29 if (maxIndex != index) { 30 CommonUtils.swap(toSort, index, maxIndex); 31 adjustHeap(toSort, maxIndex, size); 32 } 33 34 } 35 36 /** 37 * 38 * @param toSort 39 * array to sort 40 */ 41 private void buildHeap(int[] toSort) { 42 int lastNonLeaf = toSort.length / 2 - 1; 43 for (int i = lastNonLeaf; i >= 0; i--) { 44 adjustHeap(toSort, i, toSort.length); 45 } 46 }