简体   繁体   中英

Heap Bit-Shift Macros for Left, Right and Parent

I am reading about Heaps, which describes that you can do the operations of accessing the left child, the RIGHT / LEFT child and the PARENT with bit shift operations. While Left and Parent seems trivial i am not sure with the right one. Do i just have to add one?

Here is an excerpt from the book: MIT Introduciton to algorithms:

"Similarly, the RIGHT procedure can quickly compute 2i + 1 by shifting the binary representation of i left by one bit position and then adding in a 1 as the low-order bit".

麻省理工学院算法概论-堆

Access Operations:

LEFT: 2*i

i<<1

RIGHT: 2*i+1

(i<<1)+1

PARENT: i/2

i>>1

This is how heap works - for every node you could easily get:

  1. Parent - just divide the node index by two ( N / 2 )
  2. Left child - multiply index by two ( N * 2 )
  3. Right child - multiply index by two and increase new index by one ( N * 2 + 1 )

It is easy to prove, that two distinct nodes cannot have same child.

Suppose, N1 , N2 and C are heap nodes. N1 != N2 and C.is_child_of(N1) and C.is_child_of(N2) , where C.is_child_of(N) returns true when C is either right or left child of N . Then:

  1. If C is the left child of both N1 and N2 , then N1 * 2 = N2 * 2 <=> N1 = N2
  2. Similarly, if C is the right child of both N1 and N2 , then N1 * 2 + 1 = N2 * 2 + 1 <=> N1 = N2
  3. If C is the left child of N1 and C is the right child of N2 , then N1 * 2 = N2 * 2 + 1 which is incorrect, because N1 * 2 is even and N2 * 2 + 1 is odd.

Note, that your bitwise access operations are incorrect - you should shift indices by one, not by two, because N << M is N * 2^M . I'd also suggest you to use plain division / multiplication instead of bit shifting - the compiler knows how to optimize your code.

A left shift by one bit position on an Int i is equivalent to 2*i

If we consider i as the index of an array:
- the index of the left child can be obtained using:

i << 1

-the index of the right child

(i<<1)+1

-The parent:

i>>1

(equivalent to i/2)

Don't forget we consider on this case that the initial index of the array is 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM