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