Question: What can you say about the value contained at the root of a max heap?
Reminder:
This array is already a heap. The root is a[1]
.
int n = N; //Initial build of Max Heap from bottom up for(i= N/2; i>0; i--) siftDown(i,n); // do { swap(1,n); //move biggest in heap to the end; move value of a[n] to root n--; //heap is now one smaller; siftDown(1,n); //now its a max heap } while(n>1);
void siftDown(int i, int n) //expects: two plug-in values: // i, a node specified by its index in the array, // and n, the index of the last item in the heap. //expects: that the left and right subtrees of node i // are either empty or are already max heaps //process: the function will swap values within the // the subtree based at i. // result: subtree based at i is now a max heap
void siftDown(int i, int n) { int lc; while (lc = bigChildExists(i,n)) { swap(lc,i); i = lc; } }
int bigChildExists(int i, int n) // i,n as above // returns 0 if no child of i has value larger than a[i] // otherwise returns the index of the largest child