I am learning about Binary Heaps and I understand that to get the left child the formula is (2 x index)+1
and to get the right child is (2 x index)+2
. That makes sense to me but getting the parent node is where I don't really understand. I know the formula for that is (index - 1) / 2
but how does it work if it returns a half (.5
)?
For example, if I am trying to find the parent node of index 3
then that would be (3-1)/2
which gives you 1
so that makes sense but what about index 4
? That would be (4-1)/2
which gives you 1.5
. So would the parent of index 4
be index 1
or index 2
? Looking at a diagram like the one below it makes sense obviously because index 4
is tied to index 1
but from a mathematics standpoint I'm just not sure I understand how to handle it when halves come into play.
Thank you!