Commit 62abc2f6 authored by Tim Peters's avatar Tim Peters

heappop(): Added comments; simplified and sped the code.

parent 1acab695
...@@ -142,27 +142,25 @@ def heappop(heap): ...@@ -142,27 +142,25 @@ def heappop(heap):
returnitem = heap[0] returnitem = heap[0]
item = heap.pop() item = heap.pop()
pos = 0 pos = 0
while True: # Sift item into position, down from the root, moving the smaller
child2pos = (pos + 1) * 2 # child up, until finding pos such that item <= pos's children.
child1pos = child2pos - 1 childpos = 2*pos + 1 # leftmost child position
if child2pos < endpos: while childpos < endpos:
child1 = heap[child1pos] # Set childpos and child to reflect smaller child.
child2 = heap[child2pos] child = heap[childpos]
if item <= child1 and item <= child2: rightpos = childpos + 1
break if rightpos < endpos:
if child1 < child2: rightchild = heap[rightpos]
heap[pos] = child1 if rightchild < child:
pos = child1pos childpos = rightpos
continue child = rightchild
heap[pos] = child2 # If item is no larger than smaller child, we're done, else
pos = child2pos # move the smaller child up.
continue if item <= child:
if child1pos < endpos: break
child1 = heap[child1pos] heap[pos] = child
if child1 < item: pos = childpos
heap[pos] = child1 childpos = 2*pos + 1
pos = child1pos
break
heap[pos] = item heap[pos] = item
return returnitem return returnitem
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment