Like the title says, I would like to know if python's heapq.heapify() will work faster on a list that is close to a heap or does it do the entire operation element by element on every list?
I'm debating on how often to use heapify().
Like the title says, I would like to know if python's heapq.heapify() will work faster on a list that is close to a heap or does it do the entire operation element by element on every list?
I'm debating on how often to use heapify().
Copyright © 2021 Jogjafile Inc.
The obvious answer is yes. If you supply a sorted array to
heapifyit won't have to perform any swaps at all. If you supply a reverse-sorted array it will have to perform the maximum number of swaps.That said, there is no benefit to pre-sorting the array before passing it to
heapifybecause the total time (i.e. analyzing and arranging the array, plusheapifytime) will exceed the maximum time required forheapifyto do its work on even the worst-case arrangement.That said, you shouldn't have to call
heapifymore than once. That is, you callheapifyto construct the heap. Then you call theheappushandheappopmethods to add and remove items.I suppose, if you have to add a large number of items to an existing heap, you could append them to an existing heap and then call
heapifyto re-build the heap. Hard to say the exact circumstances under which that would be useful. I'd certainly give any such code a big ol' WTF if I were to see it in a code review.