I am trying to implement max heapify algorithm given in Algorithms Book here The algo in book is
MAX-HEAPIFY(A,i)
1 l<-LEFT(i)
2 r<-RIGHT(i)
3 if l<=heap-size[A] and A[l]>A[i]
4 then largest<--l
5 else largest<--i
6 if r<=heap-size[A] and A[r]>A[largest]
7 then largest <->r
8 if largest!=i
9 then exchange A[i]<->A[largest]
10 MAX-HEAPIFY(A,largest)
My problem is my array is starting at Zero.Where as in book they assumed that if i开发者_开发知识库ndex of parent is i then left child is 2i and right child is 2i+1 but that is when their indices start from 1.In my case it is zero so what how should I calculate index of left and right child?
The left child is at 2i+1, the right child is at 2(i+1) = 2i+2.
You can prove that this is correct by calling your one-based indices j, defining i = j - 1 and observing that
j = i + 1
left + 1 = 2j = 2(i+1) = 2i+2
right + 1 = 2j+1 = 2(i+1) + 1
so
left = 2i+1
right = 2(i+1)
(You can also save yourself some trouble by overallocating a single element.)
精彩评论