0

the first heappop() is not the min of array, while it's the first index.

After that, heappop() works

I thought maybe it's the automatic heapify() after heappop()? check the documents but find nothing

>>> a = [412,23,24,24,32,5,324,12,41,125,5,32,41,24,12,5,34,1]
>>> heappop(a)
412
>>> heappop(a)
1
>>> heappop(a)
23
>>> a
[24, 24, 5, 12, 32, 32, 324, 5, 41, 125, 5, 34, 41, 24, 12]

BTW, if you heapify() a at first, the heappop() works well. Would be appreciated if any explanation on it. Thank you!

>>> a = [412,23,24,24,32,5,324,12,41,125,5,32,41,24,12,5,34,1]
>>> heapify(a)
>>> a
[1, 5, 5, 5, 32, 24, 12, 12, 24, 125, 412, 32, 41, 24, 324, 23, 34, 41]
>>> heappop(a)
1
>>> heappop(a)
5
>>> heappop(a)
5
>>> heappop(a)
5
>>> heappop(a)
12
Cici Hou
  • 3
  • 1
  • 3
    This is the expected behavior. The first time you start using a regular list as a heap, you have to ```heapify()``` it to ensure it's in heap-sorted order. Successive uses of ```heappop()``` or ```heappush()``` will automatically keep it sorted. – sj95126 Sep 23 '21 at 23:33
  • 2
    `heappop` will *maintain* the heap invariant of a list that already satisfies the heap invariant, but I don't think it (or any arbitrary series of heap operations) is guaranteed to turn a list into a heap. `heapify`itself performs a *specific* set of operations turn the list into a heap. – chepner Sep 23 '21 at 23:53
  • Just an added note: in your example, `heappop` is *not* working correctly after the first use. Notice how it returns `23` as the third value, skipping the `5`s and `12`. (As others have pointed out, this is because it's still not a heap.) – CrazyChucky Sep 24 '21 at 15:43
  • @CrazyChucky Thanks for your reminding, you mean it's not a heap and seems to just pop value from the list randomly? I've not think about that – Cici Hou Sep 25 '21 at 18:15

1 Answers1

2

The documentation says:

To create a heap, use a list initialized to [], or you can transform a populated list into a heap via function heapify().

As you have not done this in the first code block, your list is not a heap.

Functions like heappush, heappop, heappushpop, heapreplace maintain the heap invariant. But this implies that the list should be a heap before the call is made. Only then is it guaranteed that the list will still be a heap after the call.

These methods have a O(logn) time complexity, so they could not possibly make a heap from any random list. heapify has a time complexity of O(n). The power of a heap is that once you have established it, you can make use of the efficient methods to handle it, without having to call the more expensive heapify again.

trincot
  • 317,000
  • 35
  • 244
  • 286