[英]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. 我正在阅读有关堆的文章,该文章描述了您可以通过位移操作来访问左子项, RIGHT / LEFT子项和PARENT 。 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: 这是本书的摘录:MIT算法简介:
"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". “类似地, RIGHT过程可以通过将i的二进制表示左移一位位置,然后再添加1作为低阶位来快速计算2i +1。”
Access Operations: 访问操作:
LEFT: 2*i 左:2 * i
i<<1
RIGHT: 2*i+1 右:2 * i + 1
(i<<1)+1
PARENT: i/2 父母:i / 2
i>>1
This is how heap works - for every node you could easily get: 这是堆的工作方式-对于每个节点,您都可以轻松获得:
N / 2
) N / 2
) N * 2
) N * 2
) N * 2 + 1
) 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
和C
是堆节点。 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
. N1 != N2
以及C.is_child_of(N1)
和C.is_child_of(N2)
,其中C.is_child_of(N)
当C
是N
左或右子C.is_child_of(N)
时返回true
。 Then: 然后:
C
is the left child of both N1
and N2
, then N1 * 2 = N2 * 2 <=> N1 = N2
C
是N1
和N2
的左子代,则N1 * 2 = N2 * 2 <=> N1 = N2
C
is the right child of both N1
and N2
, then N1 * 2 + 1 = N2 * 2 + 1 <=> N1 = N2
C
是N1
和N2
的右子,则N1 * 2 + 1 = N2 * 2 + 1 <=> N1 = N2
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. C
是N1
的左子代,而C
是N2
的右子代,则N1 * 2 = N2 * 2 + 1
是不正确的,因为N1 * 2
为偶数, N2 * 2 + 1
为奇数。 Note, that your bitwise access operations are incorrect - you should shift indices by one, not by two, because N << M
is N * 2^M
. 请注意,按位访问操作不正确-您应该将索引移位1,而不是2,因为
N << M
为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
Int i
上左移一位的位置等于2*i
If we consider i as the index of an array: 如果我们将i作为数组的索引:
- 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) (相当于i / 2)
Don't forget we consider on this case that the initial index of the array is 1. 不要忘记我们在这种情况下认为数组的初始索引为1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.