prove that in binary heap buildheap function does at most 2N-2 comparison I don't know how should I prove it I need some hint thanks.
buildheap procedure: we have n element and we build a heap at first and then we start from the first node which is not leaf(floor of n/2) and for each step we have 2 comparison(each node should be compared with min of children and to find min also there is 1 comparison) so we compare this node and we go back until we get to root(and all of these steps are recursive and keeps continuing till we reach the node or right place of node)
buildheap():
for i ← size / 2 till i > 0
Max-Heapify(i)
i ← i-1
Max-Heapify(A, i):
left ← 2×i
right ← 2×i + 1
largest ← i
if left ≤ length(A) and A[left] > A[largest] then:
largest ← left
if right ≤ length(A) and A[right] > A[largest] then:
largest ← right
if largest ≠ i then:
swap A[i] and A[largest]
Max-Heapify(A, largest)
I wrote number of comparisons:
node comparison
1 0
2 1
3 2
4 3
5 6
6 7
7 8
8 11
9 14
I think the worst case is when we have new level with one node(3,5,9,.. node because it has 2 less than the most we have)
but I have another idea:
we have n/2 node which don't move down
n/4 moves one level down
n/8 moves 3 level down
and each moving from level to level needs 2 comparison so we have
$\frac{n}{2} \times 0 + \frac{n}{4} \times 1 + \frac{n}{8} \times 2 + .... = n \times (\frac{1}{4} + \frac{2}{8} + \frac{3}{{16}} + \frac{4}{{32}} + ...)$
sum of $(\frac{1}{4} + \frac{2}{8} + \frac{3}{{16}} + \frac{4}{{32}} + ...)$ is $1$ and it will be multiplied by 2(because of 2 comparison for each move) but we have 2n here not 2n-2
did I make a mistake or the idea is wrong?
we have n/2 node which don't move
- with the root on top, I have n/2 node which don't move down. $\endgroup$