blob: cb22a194f085b15791838b00e8f9ccf72f12ea23 [file] [log] [blame]
Guido van Rossum4b48d6b2002-08-02 20:23:56 +00001# -*- coding: Latin-1 -*-
2
Guido van Rossum0a824382002-08-02 16:44:32 +00003"""Heap queue algorithm (a.k.a. priority queue).
4
5Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
6all k, counting elements from 0. For the sake of comparison,
7non-existing elements are considered to be infinite. The interesting
8property of a heap is that a[0] is always its smallest element.
9
10Usage:
11
12heap = [] # creates an empty heap
13heappush(heap, item) # pushes a new item on the heap
14item = heappop(heap) # pops the smallest item from the heap
15item = heap[0] # smallest item on the heap without popping it
16
17Our API differs from textbook heap algorithms as follows:
18
19- We use 0-based indexing. This makes the relationship between the
20 index for a node and the indexes for its children slightly less
21 obvious, but is more suitable since Python uses 0-based indexing.
22
23- Our heappop() method returns the smallest item, not the largest.
24
25These two make it possible to view the heap as a regular Python list
26without surprises: heap[0] is the smallest item, and heap.sort()
27maintains the heap invariant!
28"""
29
Guido van Rossum37c3b272002-08-02 16:50:58 +000030# Code by Kevin O'Connor
31
Guido van Rossum0a824382002-08-02 16:44:32 +000032__about__ = """Heap queues
33
34[explanation by François Pinard]
35
36Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
37all k, counting elements from 0. For the sake of comparison,
38non-existing elements are considered to be infinite. The interesting
39property of a heap is that a[0] is always its smallest element.
40
41The strange invariant above is meant to be an efficient memory
42representation for a tournament. The numbers below are `k', not a[k]:
43
44 0
45
46 1 2
47
48 3 4 5 6
49
50 7 8 9 10 11 12 13 14
51
52 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
53
54
55In the tree above, each cell `k' is topping `2*k+1' and `2*k+2'. In
56an usual binary tournament we see in sports, each cell is the winner
57over the two cells it tops, and we can trace the winner down the tree
58to see all opponents s/he had. However, in many computer applications
59of such tournaments, we do not need to trace the history of a winner.
60To be more memory efficient, when a winner is promoted, we try to
61replace it by something else at a lower level, and the rule becomes
62that a cell and the two cells it tops contain three different items,
63but the top cell "wins" over the two topped cells.
64
65If this heap invariant is protected at all time, index 0 is clearly
66the overall winner. The simplest algorithmic way to remove it and
67find the "next" winner is to move some loser (let's say cell 30 in the
68diagram above) into the 0 position, and then percolate this new 0 down
69the tree, exchanging values, until the invariant is re-established.
70This is clearly logarithmic on the total number of items in the tree.
71By iterating over all items, you get an O(n ln n) sort.
72
73A nice feature of this sort is that you can efficiently insert new
74items while the sort is going on, provided that the inserted items are
75not "better" than the last 0'th element you extracted. This is
76especially useful in simulation contexts, where the tree holds all
77incoming events, and the "win" condition means the smallest scheduled
78time. When an event schedule other events for execution, they are
79scheduled into the future, so they can easily go into the heap. So, a
80heap is a good structure for implementing schedulers (this is what I
81used for my MIDI sequencer :-).
82
83Various structures for implementing schedulers have been extensively
84studied, and heaps are good for this, as they are reasonably speedy,
85the speed is almost constant, and the worst case is not much different
86than the average case. However, there are other representations which
87are more efficient overall, yet the worst cases might be terrible.
88
89Heaps are also very useful in big disk sorts. You most probably all
90know that a big sort implies producing "runs" (which are pre-sorted
91sequences, which size is usually related to the amount of CPU memory),
92followed by a merging passes for these runs, which merging is often
93very cleverly organised[1]. It is very important that the initial
94sort produces the longest runs possible. Tournaments are a good way
95to that. If, using all the memory available to hold a tournament, you
96replace and percolate items that happen to fit the current run, you'll
97produce runs which are twice the size of the memory for random input,
98and much better for input fuzzily ordered.
99
100Moreover, if you output the 0'th item on disk and get an input which
101may not fit in the current tournament (because the value "wins" over
102the last output value), it cannot fit in the heap, so the size of the
103heap decreases. The freed memory could be cleverly reused immediately
104for progressively building a second heap, which grows at exactly the
105same rate the first heap is melting. When the first heap completely
106vanishes, you switch heaps and start a new run. Clever and quite
107effective!
108
109In a word, heaps are useful memory structures to know. I use them in
110a few applications, and I think it is good to keep a `heap' module
111around. :-)
112
113--------------------
114[1] The disk balancing algorithms which are current, nowadays, are
115more annoying than clever, and this is a consequence of the seeking
116capabilities of the disks. On devices which cannot seek, like big
117tape drives, the story was quite different, and one had to be very
118clever to ensure (far in advance) that each tape movement will be the
119most effective possible (that is, will best participate at
120"progressing" the merge). Some tapes were even able to read
121backwards, and this was also used to avoid the rewinding time.
122Believe me, real good tape sorts were quite spectacular to watch!
123From all times, sorting has always been a Great Art! :-)
124"""
125
126def heappush(heap, item):
127 """Push item onto heap, maintaining the heap invariant."""
128 pos = len(heap)
129 heap.append(None)
130 while pos:
Tim Petersd9ea39d2002-08-02 19:16:44 +0000131 parentpos = (pos - 1) >> 1
Guido van Rossum0a824382002-08-02 16:44:32 +0000132 parent = heap[parentpos]
133 if item >= parent:
134 break
135 heap[pos] = parent
136 pos = parentpos
137 heap[pos] = item
138
139def heappop(heap):
140 """Pop the smallest item off the heap, maintaining the heap invariant."""
141 endpos = len(heap) - 1
142 if endpos <= 0:
143 return heap.pop()
144 returnitem = heap[0]
145 item = heap.pop()
146 pos = 0
Tim Peters62abc2f2002-08-02 20:09:14 +0000147 # Sift item into position, down from the root, moving the smaller
148 # child up, until finding pos such that item <= pos's children.
149 childpos = 2*pos + 1 # leftmost child position
150 while childpos < endpos:
151 # Set childpos and child to reflect smaller child.
152 child = heap[childpos]
153 rightpos = childpos + 1
154 if rightpos < endpos:
155 rightchild = heap[rightpos]
156 if rightchild < child:
157 childpos = rightpos
158 child = rightchild
159 # If item is no larger than smaller child, we're done, else
160 # move the smaller child up.
161 if item <= child:
162 break
163 heap[pos] = child
164 pos = childpos
165 childpos = 2*pos + 1
Guido van Rossum0a824382002-08-02 16:44:32 +0000166 heap[pos] = item
167 return returnitem
168
169if __name__ == "__main__":
170 # Simple sanity test
171 heap = []
172 data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
173 for item in data:
174 heappush(heap, item)
175 sort = []
176 while heap:
177 sort.append(heappop(heap))
178 print sort