CS 3343/3341 Analysis of Algorithms |
Heaps,
Heapsort, and Priority Queues |
Here are details about heaps and the heapsort algorithm.
Remark: For a commercial program, one should create the heap data type in Java or C++ as an Abstract Data Type, using a class for the implementation. Java provides a library priority queue based on a heap, and C++ also provides a library priority queue more explicitly based on a heap, and one of these would be an even better choice for a commercial program. In this course we are learning how these types work, and for simplicity might use a "trick" such as storing the heapsize in the 0th array element.
|
Above, if 2*i > A.heapsize, then there is no left child, and similarly if 2*i + 1 > A.heapsize, then there is no right child.
A[Parent(i)] >= A[i], for every node i except the root, that is, 2 <= i && i <= A.heapsize. |
MaxHeapify(A, i) l = Left(i) r = Right(i) if (l <= A.heapsize && A[l] > A[i]) largest = l else largest = i if (r <= A.heapsize && A[r] > A[largest]) largest = r if (largest != i) exchange(A[i], A[largest]) MaxHeapify(A, largest) |
BuildMaxHeap(A) A.heapsize = n for (i = floor(n/2); i >= 1; i--) MaxHeapify(A, i) |
Heapsort(A) BuildMaxHeap(A) for (i = n; i >= 2; i--) exchange(A[1], A[i]) A.heapsize-- MaxHeapify(A, 1) |
HeapExtractMax(A) if (A.heapsize < 1) error("Heap underflow") max = A[1] A[1] = A[A.heapsize] A.heapsize-- MaxHeapify(A, 1) return max |
HeapIncreaseKey(A, i, key) if (key < A[i]) error("New key smaller than old") A[i] = key while (i > 1 && A[Parent(i)] < A[i]) exchange(A[i], A[Parent(i)]) i = Parent(i) |
MaxHeapInsert(A, key) A.heapsize++ A[A.heapsize] = -infinity HeapIncreaseKey(A, A.heapsize, key) |