5 | 11 | 17 | 21 | 19 | 31 | 37 | 29 | 41 |
heapifyUp(n)
Input: n, the index of the node we are trying to swap up
Assumes the heap is stored in an array A
if n != 1 && A[n] < A[parent(n)] swap(n, parent(n)) heapifyUp(parent(n))
Removing an element:
heapifyDown(A, n):
Input: the heap array, A; the index of the node that is out of place, n
Postcondition: the node will (eventually) end up in the correct spot
smallest = n l = leftChild(n) r = rightChild(n) if l <= index && A[l] < A[smallest] smallest = l if r <= index && A[r] < A[smallest] smallest = r if smallest != n swap(smallest, n) heapifyDown(A, smallest)
Heap sort:
heapSort(A)
Input: An unsorted array, A
Postcondition: A is sorted in descending order
buildHeap(A) for i = index down to 1 swap(i, 1) decrement index heapifyDown(1)
buildHeap(A):
Input: An array, A
Postcondition: A is valid heap (heap order property is upheld)
for i = index/2 down to 1 heapifyDown(i)