// indexing starts at 1 (not 0)
int parent(int k) {return k/2; }
int left(int k) {return 2k; }
int right(int k) {return 2k+1; }
// max-heap property (at location k): q[k] ≥ q[left(k)] and q[k] ≥ q[right(k)]
// Definition: a max-heap is an array of n items with the heap property at locations 1..n.
void heapify1(array q, int n) {
// Input: q is an array of n items
// Output: q is permuted to be a max-heap
for (int i = 2; i <= n; ++i)
bubble_up(q, i);
}
void bubble_up(array q, int k) {
// Input: k is a valid index in q, a max-heap of size k,
except that max-heap property may be violated at parent[k].
// Output: q is permuted to be a max-heap
if (not parent(k) or q[parent(k) >= q[k]) return;
swap(q[parent(k)],q[k]);
bubble_up(q, parent(k));
}
void heapify2(q, n) {
// Input: q is an array of n items
// Output: q is permuted to be a max-heap
for (int i = n/2; i > 0; --i)
bubble_down(q, i);
}
void bubble_down(array q, int k) {
// Input: k is a valid index in q.
// q has the heap property at locations k+1 through n.
// Output: q is permuted to have the heap property at locations k through n.
if (/*right(k) > n and*/ left(k) > n) return;
// set d to index of dominant child.
if (right(k) > n or q[right(<)] >= q[left(k)]) d = left(k);
else d = right(k);
if (q[d] >= q[k]){
swap(q[d],q[k]);
bubble_down(q, d, n);
}
Worst case number of comparisons questions.
n is one less than a power of 2, n = 2k.
Question 1: How many array element comparisons does heapify1 do when n is 7?
Question 2: How many array element comparisons does heapify2 do when n is 7?
Question 3: How many array element comparisons does heapify1 do when n is 15?
Question 4: How many array element comparisons does heapify2 do when n is 15?
Question 5: write a summation formula for the cost of heapify1.
Question 6: write a summation formula for the cost of heapify6.
Question 7: Show that heapify1 worst case comparisons is Θ(nlg(n)).
Question 8: Show that heapify8 worst case comparisons is Θ(n).