This is a homework question, and I’m asked to show that 8 element Binary Heap needs 8 comparisons.
but when I use an example such: 1 2 3 4 5 6 7 8
I’m not sure if I should go bottom up or top down.
but anyways, I’ve tried them both.
In top down:
I’ve done it in 8 steps but when I count the number of comparisons I get 13 :S
In bottum up:
I’ve done it in 7 steps but when I count the number of comparisons I get 10 :S
After Trying the algorithm here is the comparisons I got:
- H[L]=8 > H[i]=4
- H[L]=8 > H[i]=2, H[r]=5 > H[Largest]=8
- H[L]=4 > H[i]=2
- H[L]=6 > H[i]=3, H[r]=7 > H[Largest]=6
- H[L]=8 > H[i]=1, H[r]=7 < H[Largest]=8
- H[L]=4 > H[i]=1, H[r]=5 > H[Largest]=4
hmmm, any help on how should I count the number of comparisons so I can show them 8?
and what method shall I use(bottom up or top down)?
Building a Heap bottom-up is linear, top-down (or incrementally) is
O(n log n).Try to follow the actual algorithm, don’t just draw trees. I’ve seen that in too many exams, people drawing pretty trees but not following the alogrithm, which usually leads to incorrect results, inefficiencies etc. The tree is just the ‘idea’, not the ‘method’. The method here actually uses an array.
Edit: bottom up starts at half of the heap size. So at element 4, and 7 comparisons:
Edit2: Max heap:
Makes 10 comparisons. So I believe that either your homework question had an error, or you reported the question incorrectly. That building a heap bottom-up is
O(n)doesn’t mean it takes exactlyncomparisons. For the exact bounds, check a textbook.