关键在于最大堆的建立和重构 (其实两个过程是一样的)
因为堆是平衡二叉树, 所以数组可以直接用下标表示父子的节点关系, 数组要从下标1开始.
将最大值移到数组只需要O(n)
重构堆需要O(lgn)
所以upper bound is O(n*logn)
事实上, lower bound is Ω(n*logn)
最好最坏最差都是O(n*logn)
Pseudocode
heapSort (arr, len)
{
buildMaxHeap()
for () {
remove the root element(the max) to the end of array
reconstructHeap();
}
}
reconsturctHeap(arr, len)
{
tmp = arr[root]
get the children of root
while () {
get the bigger child between left and right child
if the element of that child is larger than root
replace its parent element with is
move to next children
}
place the tmp to the apporpriate pos
}
Java
package ncku.cdc.sorting;
import java.util.Random;
public class HeapSort {
private int[] sequence;
public HeapSort(int size, int range) {
sequence = new int[size + 1];
Random rand = new Random();
for (int i = 1; i <= size; i++) {
sequence[i] = rand.nextInt(range);
}
}
public static void main(String[] args) {
int size = Integer.valueOf(args[0]);
int range = Integer.valueOf(args[1]);
HeapSort heap = new HeapSort(size, range);
System.out.println("before heapSort:");
SortingTools.validation(heap.getSequence(), 1);
heap.heapSort(heap.getSequence(), size);
System.out.println("after heapSort:");
SortingTools.validation(heap.getSequence(), 1);
}
public void heapSort(int[] arr, int len) {
for (int i = len / 2; i > 0; i--) {
retifyHeap(arr, i, len);
}
for (int j = len - 1; j > 0; j--) {
swap(arr, 1, j + 1);
retifyHeap(arr, 1, j);
}
}
private void retifyHeap(int[] arr, int root, int len) {
int tmp = arr[root];
int child = root * 2;
while (child <= len) {
if ((child < len) && (arr[child] < arr[child + 1])) { child++; }
if (tmp > arr[child]) { break; }
else {
arr[child / 2] = arr[child];
child *= 2;
}
}
arr[child / 2] = tmp;
}
private void swap(int[] arr, int i, int j) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
public int[] getSequence() {
return sequence;
}
}
程序输出:
before heapSort:
67 18 192 142 136 30 144 6 158 11 123 34 36 155 97 12 7 159 81 135 160 102 48 42 0 155 77 114 139 146 186 32 42 144 100
after heapSort:
0 6 7 11 12 18 30 32 34 36 42 42 48 67 77 81 97 100 102 114 123 135 136 139 142 144 144 146 155 155 158 159 160 186 192