Python:
def _siftdown(heap, startpos, pos):
newitem = heap[pos]
# Follow the path to the root, moving parents down until finding a place
# newitem fits.
while pos> startpos:
parentpos = (pos - 1)>> 1
parent = heap[parentpos]
if cmp_lt(newitem, parent):
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem
我能解释一下6号源代码吗?什么是运算符及其工作原理?在
>>
运算符表示bitwise right shift。将(非负整数)右移一位相当于除以2并向下取整。换句话说,spam >> 1
和{那么,为什么要使用
>>
?一些CPU,尤其是较老的CPU,可以比除法更快地进行数量级的位移位。大多数现代的C编译器会在适当的时候将n / 2
优化为n >> 1
,但是旧的编译器不会。当然,这在Python中几乎没有什么区别,但是大多数传统的堆实现(您在数据结构教科书中看到的类型)将使用>>
。除此之外,对于某些人(从教科书中学习到的那种人),算法中的>>
是一个很好的信号,表明它是对数的。在阅读the documentation的顶部:
因此,对于}。正如下一段所述,这可能会令人困惑:
k=1
,子元素是2*1+1 = 3
和{因此,您期望},但是如果您用基于0的术语来考虑它,您应该期望}和{},而{}的子元素是{}和{}。在
1
的子元素是2
和{0
的子元素是{>>
是右移位运算符。它删除最右边的位,这与除以2并忽略余数相同。所以这行可能是parentpos = (pos - 1) // 2
。在Python的堆是从零开始的,因此节点i在}处有子节点。它的父节点位于
2 * i + 1
和{(i - 1) // 2
。在siftdown的作用是向上移动一个值(通过与父对象交换),直到父对象小于子对象。在
相关问题 更多 >
编程相关推荐