[issue21185] heapq fails to print in sorted order for certain inputs

Saimadhav Heblikar report at bugs.python.org
Wed Apr 9 10:23:11 CEST 2014


Saimadhav Heblikar added the comment:

Hi,
I dont think its a bug. 
The textbook definition of a min(or max) heap is

"Heaps are binary trees for which every parent node has a value less than or equal to any of its children."

Therefore,
when lista = [1,6,5,4], and heapify is run on it,it can be viewed as
    1
  /   \
4  5  6

or [1,4,5,6]

When listb=[1,6,5], running heapify on it,gives
   1
  / \
 6   5

or [1,6,5]
heapify maintains the heap-invariant - Every key is smaller than its children. This invariant is not violated in the above example.

The heappop maintains the heap-invariant after popping. The line in your code
[heapq.heappop(listb) for i in range(len(listb))]
is the heapsort algorithm!.

Hopefully, this clears your question.

----------
nosy: +sahutd

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue21185>
_______________________________________


More information about the Python-bugs-list mailing list