@@ -25,13 +25,16 @@ \section{\module{heapq} ---
2525(a) We use zero-based indexing. This makes the relationship between the
2626index for a node and the indexes for its children slightly less
2727obvious, but is more suitable since Python uses zero-based indexing.
28- (b) Our pop method returns the smallest item, not the largest.
28+ (b) Our pop method returns the smallest item, not the largest (called a
29+ "min heap" in textbooks; a "max heap" is more common in texts because
30+ of its suitability for in-place sorting).
2931
3032These two make it possible to view the heap as a regular Python list
3133without surprises: \code {\var {heap}[0]} is the smallest item, and
3234\code {\var {heap}.sort()} maintains the heap invariant!
3335
34- To create a heap, use a list initialized to \code {[]}.
36+ To create a heap, use a list initialized to \code {[]}, or you can
37+ transform a populated list into a heap via function \function {heapify()}.
3538
3639The following functions are provided:
3740
@@ -45,6 +48,10 @@ \section{\module{heapq} ---
4548heap invariant.
4649\end {funcdesc }
4750
51+ \begin {funcdesc }{heapify}{x}
52+ Transform list \var {x} into a heap, in-place, in linear time.
53+ \end {funcdesc }
54+
4855Example of use:
4956
5057\begin {verbatim }
@@ -53,17 +60,17 @@ \section{\module{heapq} ---
5360>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
5461>>> for item in data:
5562... heappush(heap, item)
56- ...
63+ ...
5764>>> sorted = []
5865>>> while heap:
5966... sorted.append(heappop(heap))
60- ...
67+ ...
6168>>> print sorted
6269[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
6370>>> data.sort()
6471>>> print data == sorted
6572True
66- >>>
73+ >>>
6774\end {verbatim }
6875
6976
0 commit comments