The algorithms for finding the parent and children for heaps are:
Parent: i / 2
Left child: 2i
Right child: 2i + 1
I’ve tried drawing out the array representation on paper, but I’m not sure I totally intuitively get it.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The key is that the elements are enumerated in a breadth-first fashion and that the indexes are 1-based (they begin at 1 and not 0).
Take 3 for example
Dividing both 6 and 7 by 2 give 3, at least in languages that do integer division.
Continue numbering in this fashion and your intution should kick in. In general, multiplying by 2 will always give the index of the left child. The right child is the successor (+1) of the left child. Integer division by 2 works for the same reason (it “throws away” the remainder.)