blob: 8a6a4f5cc13df856ca92656299497c74bef3378f [file] [log] [blame]
Raymond Hettingerb3af1812003-11-08 10:24:38 +00001/* Drop in replacement for heapq.py
2
3C implementation derived directly from heapq.py in Py2.3
4which was written by Kevin O'Connor, augmented by Tim Peters,
5annotated by François Pinard, and converted to C by Raymond Hettinger.
6
7*/
8
9#include "Python.h"
10
11int
12_siftdown(PyListObject *heap, int startpos, int pos)
13{
14 PyObject *newitem, *parent;
15 int cmp, parentpos;
16
17 if (pos >= PyList_GET_SIZE(heap)) {
18 PyErr_SetString(PyExc_IndexError, "index out of range");
19 return -1;
20 }
21
22 newitem = PyList_GET_ITEM(heap, pos);
23 Py_INCREF(newitem);
24 /* Follow the path to the root, moving parents down until finding
25 a place newitem fits. */
26 while (pos > startpos){
27 parentpos = (pos - 1) >> 1;
28 parent = PyList_GET_ITEM(heap, parentpos);
29 cmp = PyObject_RichCompareBool(parent, newitem, Py_LE);
30 if (cmp == -1)
31 return -1;
32 if (cmp == 1)
33 break;
34 Py_INCREF(parent);
35 Py_DECREF(PyList_GET_ITEM(heap, pos));
36 PyList_SET_ITEM(heap, pos, parent);
37 pos = parentpos;
38 }
39 Py_DECREF(PyList_GET_ITEM(heap, pos));
40 PyList_SET_ITEM(heap, pos, newitem);
41 return 0;
42}
43
44int
45_siftup(PyListObject *heap, int pos)
46{
47 int startpos, endpos, childpos, rightpos;
48 int cmp;
49 PyObject *newitem, *tmp;
50
51 endpos = PyList_GET_SIZE(heap);
52 startpos = pos;
53 if (pos >= endpos) {
54 PyErr_SetString(PyExc_IndexError, "index out of range");
55 return -1;
56 }
57 newitem = PyList_GET_ITEM(heap, pos);
58 Py_INCREF(newitem);
59
60 /* Bubble up the smaller child until hitting a leaf. */
61 childpos = 2*pos + 1; /* leftmost child position */
62 while (childpos < endpos) {
63 /* Set childpos to index of smaller child. */
64 rightpos = childpos + 1;
65 if (rightpos < endpos) {
66 cmp = PyObject_RichCompareBool(
67 PyList_GET_ITEM(heap, rightpos),
68 PyList_GET_ITEM(heap, childpos),
69 Py_LE);
70 if (cmp == -1)
71 return -1;
72 if (cmp == 1)
73 childpos = rightpos;
74 }
75 /* Move the smaller child up. */
76 tmp = PyList_GET_ITEM(heap, childpos);
77 Py_INCREF(tmp);
78 Py_DECREF(PyList_GET_ITEM(heap, pos));
79 PyList_SET_ITEM(heap, pos, tmp);
80 pos = childpos;
81 childpos = 2*pos + 1;
82 }
83
84 /* The leaf at pos is empty now. Put newitem there, and and bubble
85 it up to its final resting place (by sifting its parents down). */
86 Py_DECREF(PyList_GET_ITEM(heap, pos));
87 PyList_SET_ITEM(heap, pos, newitem);
88 return _siftdown(heap, startpos, pos);
89}
90
91PyObject *
92heappush(PyObject *self, PyObject *args)
93{
94 PyObject *heap, *item;
95
96 if (!PyArg_UnpackTuple(args, "heappush", 2, 2, &heap, &item))
97 return NULL;
98
99 if (!PyList_Check(heap)) {
100 PyErr_SetString(PyExc_ValueError, "heap argument must be a list");
101 return NULL;
102 }
103
104 if (PyList_Append(heap, item) == -1)
105 return NULL;
106
107 if (_siftdown((PyListObject *)heap, 0, PyList_GET_SIZE(heap)-1) == -1)
108 return NULL;
109 Py_INCREF(Py_None);
110 return Py_None;
111}
112
113PyDoc_STRVAR(heappush_doc,
114"Push item onto heap, maintaining the heap invariant.");
115
116PyObject *
117heappop(PyObject *self, PyObject *heap)
118{
119 PyObject *lastelt, *returnitem;
120 int n;
121
122 /* # raises appropriate IndexError if heap is empty */
123 n = PyList_GET_SIZE(heap);
124 if (n == 0) {
125 PyErr_SetString(PyExc_IndexError, "index out of range");
126 return NULL;
127 }
128
129 lastelt = PyList_GET_ITEM(heap, n-1) ;
130 Py_INCREF(lastelt);
131 PyList_SetSlice(heap, n-1, n, NULL);
132 n--;
133
134 if (!n)
135 return lastelt;
136 returnitem = PyList_GET_ITEM(heap, 0);
137 PyList_SET_ITEM(heap, 0, lastelt);
138 if (_siftup((PyListObject *)heap, 0) == -1) {
139 Py_DECREF(returnitem);
140 return NULL;
141 }
142 return returnitem;
143}
144
145PyDoc_STRVAR(heappop_doc,
146"Pop the smallest item off the heap, maintaining the heap invariant.");
147
148PyObject *
149heapreplace(PyObject *self, PyObject *args)
150{
151 PyObject *heap, *item, *returnitem;
152
153 if (!PyArg_UnpackTuple(args, "heapreplace", 2, 2, &heap, &item))
154 return NULL;
155
156 if (!PyList_Check(heap)) {
157 PyErr_SetString(PyExc_ValueError, "heap argument must be a list");
158 return NULL;
159 }
160
161 if (PyList_GET_SIZE(heap) < 1) {
162 PyErr_SetString(PyExc_IndexError, "index out of range");
163 return NULL;
164 }
165
166 returnitem = PyList_GET_ITEM(heap, 0);
167 Py_INCREF(item);
168 PyList_SET_ITEM(heap, 0, item);
169 if (_siftup((PyListObject *)heap, 0) == -1) {
170 Py_DECREF(returnitem);
171 return NULL;
172 }
173 return returnitem;
174}
175
176PyDoc_STRVAR(heapreplace_doc,
177"Pop and return the current smallest value, and add the new item.\n\
178\n\
179This is more efficient than heappop() followed by heappush(), and can be\n\
180more appropriate when using a fixed-size heap. Note that the value\n\
181returned may be larger than item! That constrains reasonable uses of\n\
182this routine.\n");
183
184PyObject *
185heapify(PyObject *self, PyObject *heap)
186{
187 int i, n;
188
189 if (!PyList_Check(heap)) {
190 PyErr_SetString(PyExc_ValueError, "heap argument must be a list");
191 return NULL;
192 }
193
194 n = PyList_GET_SIZE(heap);
195 /* Transform bottom-up. The largest index there's any point to
196 looking at is the largest with a child index in-range, so must
197 have 2*i + 1 < n, or i < (n-1)/2. If n is even = 2*j, this is
198 (2*j-1)/2 = j-1/2 so j-1 is the largest, which is n//2 - 1. If
199 n is odd = 2*j+1, this is (2*j+1-1)/2 = j so j-1 is the largest,
200 and that's again n//2-1.
201 */
202 for (i=n/2-1 ; i>=0 ; i--)
203 if(_siftup((PyListObject *)heap, i) == -1)
204 return NULL;
205 Py_INCREF(Py_None);
206 return Py_None;
207}
208
209PyDoc_STRVAR(heapify_doc,
210"Transform list into a heap, in-place, in O(len(heap)) time.");
211
212static PyMethodDef heapq_methods[] = {
213 {"heappush", (PyCFunction)heappush,
214 METH_VARARGS, heappush_doc},
215 {"heappop", (PyCFunction)heappop,
216 METH_O, heappop_doc},
217 {"heapreplace", (PyCFunction)heapreplace,
218 METH_VARARGS, heapreplace_doc},
219 {"heapify", (PyCFunction)heapify,
220 METH_O, heapify_doc},
221 {NULL, NULL} /* sentinel */
222};
223
224PyDoc_STRVAR(module_doc,
225"Heap queue algorithm (a.k.a. priority queue).\n\
226\n\
227Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\n\
228all k, counting elements from 0. For the sake of comparison,\n\
229non-existing elements are considered to be infinite. The interesting\n\
230property of a heap is that a[0] is always its smallest element.\n\
231\n\
232Usage:\n\
233\n\
234heap = [] # creates an empty heap\n\
235heappush(heap, item) # pushes a new item on the heap\n\
236item = heappop(heap) # pops the smallest item from the heap\n\
237item = heap[0] # smallest item on the heap without popping it\n\
238heapify(x) # transforms list into a heap, in-place, in linear time\n\
239item = heapreplace(heap, item) # pops and returns smallest item, and adds\n\
240 # new item; the heap size is unchanged\n\
241\n\
242Our API differs from textbook heap algorithms as follows:\n\
243\n\
244- We use 0-based indexing. This makes the relationship between the\n\
245 index for a node and the indexes for its children slightly less\n\
246 obvious, but is more suitable since Python uses 0-based indexing.\n\
247\n\
248- Our heappop() method returns the smallest item, not the largest.\n\
249\n\
250These two make it possible to view the heap as a regular Python list\n\
251without surprises: heap[0] is the smallest item, and heap.sort()\n\
252maintains the heap invariant!\n");
253
254
255PyDoc_STRVAR(__about__,
256"Heap queues\n\
257\n\
258[explanation by François Pinard]\n\
259\n\
260Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\n\
261all k, counting elements from 0. For the sake of comparison,\n\
262non-existing elements are considered to be infinite. The interesting\n\
263property of a heap is that a[0] is always its smallest element.\n"
264"\n\
265The strange invariant above is meant to be an efficient memory\n\
266representation for a tournament. The numbers below are `k', not a[k]:\n\
267\n\
268 0\n\
269\n\
270 1 2\n\
271\n\
272 3 4 5 6\n\
273\n\
274 7 8 9 10 11 12 13 14\n\
275\n\
276 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30\n\
277\n\
278\n\
279In the tree above, each cell `k' is topping `2*k+1' and `2*k+2'. In\n\
280an usual binary tournament we see in sports, each cell is the winner\n\
281over the two cells it tops, and we can trace the winner down the tree\n\
282to see all opponents s/he had. However, in many computer applications\n\
283of such tournaments, we do not need to trace the history of a winner.\n\
284To be more memory efficient, when a winner is promoted, we try to\n\
285replace it by something else at a lower level, and the rule becomes\n\
286that a cell and the two cells it tops contain three different items,\n\
287but the top cell \"wins\" over the two topped cells.\n"
288"\n\
289If this heap invariant is protected at all time, index 0 is clearly\n\
290the overall winner. The simplest algorithmic way to remove it and\n\
291find the \"next\" winner is to move some loser (let's say cell 30 in the\n\
292diagram above) into the 0 position, and then percolate this new 0 down\n\
293the tree, exchanging values, until the invariant is re-established.\n\
294This is clearly logarithmic on the total number of items in the tree.\n\
295By iterating over all items, you get an O(n ln n) sort.\n"
296"\n\
297A nice feature of this sort is that you can efficiently insert new\n\
298items while the sort is going on, provided that the inserted items are\n\
299not \"better\" than the last 0'th element you extracted. This is\n\
300especially useful in simulation contexts, where the tree holds all\n\
301incoming events, and the \"win\" condition means the smallest scheduled\n\
302time. When an event schedule other events for execution, they are\n\
303scheduled into the future, so they can easily go into the heap. So, a\n\
304heap is a good structure for implementing schedulers (this is what I\n\
305used for my MIDI sequencer :-).\n"
306"\n\
307Various structures for implementing schedulers have been extensively\n\
308studied, and heaps are good for this, as they are reasonably speedy,\n\
309the speed is almost constant, and the worst case is not much different\n\
310than the average case. However, there are other representations which\n\
311are more efficient overall, yet the worst cases might be terrible.\n"
312"\n\
313Heaps are also very useful in big disk sorts. You most probably all\n\
314know that a big sort implies producing \"runs\" (which are pre-sorted\n\
315sequences, which size is usually related to the amount of CPU memory),\n\
316followed by a merging passes for these runs, which merging is often\n\
317very cleverly organised[1]. It is very important that the initial\n\
318sort produces the longest runs possible. Tournaments are a good way\n\
319to that. If, using all the memory available to hold a tournament, you\n\
320replace and percolate items that happen to fit the current run, you'll\n\
321produce runs which are twice the size of the memory for random input,\n\
322and much better for input fuzzily ordered.\n"
323"\n\
324Moreover, if you output the 0'th item on disk and get an input which\n\
325may not fit in the current tournament (because the value \"wins\" over\n\
326the last output value), it cannot fit in the heap, so the size of the\n\
327heap decreases. The freed memory could be cleverly reused immediately\n\
328for progressively building a second heap, which grows at exactly the\n\
329same rate the first heap is melting. When the first heap completely\n\
330vanishes, you switch heaps and start a new run. Clever and quite\n\
331effective!\n\
332\n\
333In a word, heaps are useful memory structures to know. I use them in\n\
334a few applications, and I think it is good to keep a `heap' module\n\
335around. :-)\n"
336"\n\
337--------------------\n\
338[1] The disk balancing algorithms which are current, nowadays, are\n\
339more annoying than clever, and this is a consequence of the seeking\n\
340capabilities of the disks. On devices which cannot seek, like big\n\
341tape drives, the story was quite different, and one had to be very\n\
342clever to ensure (far in advance) that each tape movement will be the\n\
343most effective possible (that is, will best participate at\n\
344\"progressing\" the merge). Some tapes were even able to read\n\
345backwards, and this was also used to avoid the rewinding time.\n\
346Believe me, real good tape sorts were quite spectacular to watch!\n\
347From all times, sorting has always been a Great Art! :-)\n");
348
349PyMODINIT_FUNC
350initheapq(void)
351{
352 PyObject *m;
353
354 m = Py_InitModule3("heapq", heapq_methods, module_doc);
355 PyModule_AddObject(m, "__about__", PyString_FromString(__about__));
356}
357