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

后端 未结 4 1976
无人及你
无人及你 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:36

    As I found it in CLRS book, there is some significance in terms of performance, since generally, shift operators work very fast.

    On most computers, the LEFT procedure can compute 2*i in one instruction by simply shifting the binary representation of i left by one bit position. Similarly, the RIGHT procedure can quickly compute 2*i+1 by shifting the binary representation of i left by one bit position and then adding in a 1 as the low-order bit. The PARENT procedure can compute i/2 by shifting i right one bit position.

    So, starting the heap at index 1 will probably make faster calculation of parent, left and right child indexes.

提交回复
热议问题