Why in a heap implemented by array the index 0 is left unused?

后端 未结 4 1980
无人及你
无人及你 2020-12-23 04:12

I\'m learning data structures and every source tells me not to use index 0 of the array while implementing heap, without giving any explanation why. I searched the web, sear

4条回答
  •  星月不相逢
    2020-12-23 04:42

    As observed by AnonJ, this is a question of taste rather than technical necessity. One nice thing about starting at 1 rather than 0 is that there's a bijection between binary strings x and the positive integers that maps a binary string x to the positive integer written 1x in binary. The string x gives the path from the root to the indexed node, where 0 means "take the left child", and 1 means "take the right child".

    Another consideration is that the otherwise unused "zeroth" location can hold a sentinel with value minus infinity that, on architectures without branch prediction, may mean a non-negligible improvement in running time due to having only one test in the sift up loop rather than two.

提交回复
热议问题