heapq · Python
heapify
Rearranges a list into heap order in place, in linear time.
heapq.heapify(x, /)
Complexity
| Worst case | O(n) |
|---|---|
| Extra space | O(1) |
Sift down every internal node from the bottom up. Half the nodes are leaves and most others are near the bottom, so the sum of sift distances is O(n).
Tested example
values = [9, 4, 7, 1, 8, 2]
heapq.heapify(values) # in place, O(n)
assert values[0] == 1
assert heapq.nsmallest(3, [9, 4, 7, 1, 8, 2]) == [1, 2, 4]
max_heap = [-v for v in [9, 4, 7]] # no max-heap API: negate the keys
heapq.heapify(max_heap)
assert -max_heap[0] == 9
Parameters
- x
- Any list of comparable items.
Behaviour
- Returns
- None.
- Errors and preconditions
- TypeError if items cannot be compared.
- Changes
- Reorders the list.
- Memory and invalidation
- In place.