blob: 5e724a1ef112778b434710bb2c120e91c415c7be [file] [log] [blame]
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001/* Drop in replacement for heapq.py
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +00002
3C implementation derived directly from heapq.py in Py2.3
4which was written by Kevin O'Connor, augmented by Tim Peters,
Éric Araujo1670b432010-09-03 22:03:10 +00005annotated by François Pinard, and converted to C by Raymond Hettinger.
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +00006
7*/
8
9#include "Python.h"
10
Georg Brandlf78e02b2008-06-10 17:40:04 +000011static int
Raymond Hettinger48f68d02014-06-14 16:43:35 -070012siftdown(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000013{
Raymond Hettinger871620d2014-05-03 18:36:48 -070014 PyObject *newitem, *parent;
Raymond Hettinger90e93382014-05-03 18:45:54 -070015 Py_ssize_t parentpos, size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000016 int cmp;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000018 assert(PyList_Check(heap));
Antoine Pitrou44d52142013-03-04 20:30:01 +010019 size = PyList_GET_SIZE(heap);
20 if (pos >= size) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000021 PyErr_SetString(PyExc_IndexError, "index out of range");
22 return -1;
23 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000025 /* Follow the path to the root, moving parents down until finding
26 a place newitem fits. */
Raymond Hettinger871620d2014-05-03 18:36:48 -070027 newitem = PyList_GET_ITEM(heap, pos);
Raymond Hettinger90e93382014-05-03 18:45:54 -070028 while (pos > startpos) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000029 parentpos = (pos - 1) >> 1;
30 parent = PyList_GET_ITEM(heap, parentpos);
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +000031 cmp = PyObject_RichCompareBool(newitem, parent, Py_LT);
Raymond Hettinger871620d2014-05-03 18:36:48 -070032 if (cmp == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000033 return -1;
Antoine Pitrou44d52142013-03-04 20:30:01 +010034 if (size != PyList_GET_SIZE(heap)) {
Antoine Pitrou44d52142013-03-04 20:30:01 +010035 PyErr_SetString(PyExc_RuntimeError,
36 "list changed size during iteration");
37 return -1;
38 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000039 if (cmp == 0)
40 break;
Raymond Hettinger871620d2014-05-03 18:36:48 -070041 parent = PyList_GET_ITEM(heap, parentpos);
42 newitem = PyList_GET_ITEM(heap, pos);
43 PyList_SET_ITEM(heap, parentpos, newitem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 PyList_SET_ITEM(heap, pos, parent);
45 pos = parentpos;
46 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000047 return 0;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000048}
49
50static int
Raymond Hettinger48f68d02014-06-14 16:43:35 -070051siftup(PyListObject *heap, Py_ssize_t pos)
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000052{
Raymond Hettingerc9926082014-05-03 15:22:07 -070053 Py_ssize_t startpos, endpos, childpos, rightpos, limit;
Raymond Hettinger871620d2014-05-03 18:36:48 -070054 PyObject *tmp1, *tmp2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000055 int cmp;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000057 assert(PyList_Check(heap));
Raymond Hettinger871620d2014-05-03 18:36:48 -070058 endpos = PyList_GET_SIZE(heap);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 startpos = pos;
60 if (pos >= endpos) {
61 PyErr_SetString(PyExc_IndexError, "index out of range");
62 return -1;
63 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 /* Bubble up the smaller child until hitting a leaf. */
Raymond Hettingerc9926082014-05-03 15:22:07 -070066 limit = endpos / 2; /* smallest pos that has no child */
67 while (pos < limit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068 /* Set childpos to index of smaller child. */
Raymond Hettingerc9926082014-05-03 15:22:07 -070069 childpos = 2*pos + 1; /* leftmost child position */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000070 rightpos = childpos + 1;
71 if (rightpos < endpos) {
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +000072 cmp = PyObject_RichCompareBool(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000073 PyList_GET_ITEM(heap, childpos),
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +000074 PyList_GET_ITEM(heap, rightpos),
75 Py_LT);
Raymond Hettinger871620d2014-05-03 18:36:48 -070076 if (cmp == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 if (cmp == 0)
79 childpos = rightpos;
Raymond Hettinger871620d2014-05-03 18:36:48 -070080 if (endpos != PyList_GET_SIZE(heap)) {
81 PyErr_SetString(PyExc_RuntimeError,
82 "list changed size during iteration");
83 return -1;
84 }
Antoine Pitrou44d52142013-03-04 20:30:01 +010085 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 /* Move the smaller child up. */
Raymond Hettinger871620d2014-05-03 18:36:48 -070087 tmp1 = PyList_GET_ITEM(heap, childpos);
88 tmp2 = PyList_GET_ITEM(heap, pos);
89 PyList_SET_ITEM(heap, childpos, tmp2);
90 PyList_SET_ITEM(heap, pos, tmp1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 pos = childpos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 }
Raymond Hettinger871620d2014-05-03 18:36:48 -070093 /* Bubble it up to its final resting place (by sifting its parents down). */
Raymond Hettinger48f68d02014-06-14 16:43:35 -070094 return siftdown(heap, startpos, pos);
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000095}
96
97static PyObject *
98heappush(PyObject *self, PyObject *args)
99{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 PyObject *heap, *item;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 if (!PyArg_UnpackTuple(args, "heappush", 2, 2, &heap, &item))
103 return NULL;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 if (!PyList_Check(heap)) {
106 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
107 return NULL;
108 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000109
Raymond Hettingera032e462015-05-11 10:32:57 -0700110 if (PyList_Append(heap, item))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 return NULL;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000112
Raymond Hettingera032e462015-05-11 10:32:57 -0700113 if (siftdown((PyListObject *)heap, 0, PyList_GET_SIZE(heap)-1))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 return NULL;
Raymond Hettinger48f68d02014-06-14 16:43:35 -0700115 Py_RETURN_NONE;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000116}
117
118PyDoc_STRVAR(heappush_doc,
Raymond Hettingerbd8f2902013-01-18 17:35:25 -0800119"heappush(heap, item) -> None. Push item onto heap, maintaining the heap invariant.");
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000120
121static PyObject *
Raymond Hettinger48f68d02014-06-14 16:43:35 -0700122heappop_internal(PyObject *heap, int siftup_func(PyListObject *, Py_ssize_t))
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 PyObject *lastelt, *returnitem;
125 Py_ssize_t n;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 if (!PyList_Check(heap)) {
128 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
129 return NULL;
130 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000131
Raymond Hettinger48f68d02014-06-14 16:43:35 -0700132 /* raises IndexError if the heap is empty */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 n = PyList_GET_SIZE(heap);
134 if (n == 0) {
135 PyErr_SetString(PyExc_IndexError, "index out of range");
136 return NULL;
137 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 lastelt = PyList_GET_ITEM(heap, n-1) ;
140 Py_INCREF(lastelt);
Raymond Hettinger99bf9a22015-05-11 19:25:32 -0700141 if (PyList_SetSlice(heap, n-1, n, NULL)) {
Victor Stinner764a46d2013-07-17 21:50:21 +0200142 Py_DECREF(lastelt);
143 return NULL;
144 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 n--;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 if (!n)
148 return lastelt;
149 returnitem = PyList_GET_ITEM(heap, 0);
150 PyList_SET_ITEM(heap, 0, lastelt);
Raymond Hettingera032e462015-05-11 10:32:57 -0700151 if (siftup_func((PyListObject *)heap, 0)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 Py_DECREF(returnitem);
153 return NULL;
154 }
155 return returnitem;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000156}
157
Raymond Hettinger48f68d02014-06-14 16:43:35 -0700158static PyObject *
159heappop(PyObject *self, PyObject *heap)
160{
161 return heappop_internal(heap, siftup);
162}
163
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000164PyDoc_STRVAR(heappop_doc,
165"Pop the smallest item off the heap, maintaining the heap invariant.");
166
167static PyObject *
Raymond Hettinger48f68d02014-06-14 16:43:35 -0700168heapreplace_internal(PyObject *args, int siftup_func(PyListObject *, Py_ssize_t))
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 PyObject *heap, *item, *returnitem;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 if (!PyArg_UnpackTuple(args, "heapreplace", 2, 2, &heap, &item))
173 return NULL;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 if (!PyList_Check(heap)) {
176 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
177 return NULL;
178 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000179
Raymond Hettinger99bf9a22015-05-11 19:25:32 -0700180 if (PyList_GET_SIZE(heap) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 PyErr_SetString(PyExc_IndexError, "index out of range");
182 return NULL;
183 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 returnitem = PyList_GET_ITEM(heap, 0);
186 Py_INCREF(item);
187 PyList_SET_ITEM(heap, 0, item);
Raymond Hettingera032e462015-05-11 10:32:57 -0700188 if (siftup_func((PyListObject *)heap, 0)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 Py_DECREF(returnitem);
190 return NULL;
191 }
192 return returnitem;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000193}
194
Raymond Hettinger48f68d02014-06-14 16:43:35 -0700195static PyObject *
196heapreplace(PyObject *self, PyObject *args)
197{
198 return heapreplace_internal(args, siftup);
199}
200
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000201PyDoc_STRVAR(heapreplace_doc,
Raymond Hettingerbd8f2902013-01-18 17:35:25 -0800202"heapreplace(heap, item) -> value. Pop and return the current smallest value, and add the new item.\n\
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000203\n\
204This is more efficient than heappop() followed by heappush(), and can be\n\
205more appropriate when using a fixed-size heap. Note that the value\n\
206returned may be larger than item! That constrains reasonable uses of\n\
Raymond Hettinger8158e842004-09-06 07:04:09 +0000207this routine unless written as part of a conditional replacement:\n\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 if item > heap[0]:\n\
209 item = heapreplace(heap, item)\n");
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000210
211static PyObject *
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000212heappushpop(PyObject *self, PyObject *args)
213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 PyObject *heap, *item, *returnitem;
215 int cmp;
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 if (!PyArg_UnpackTuple(args, "heappushpop", 2, 2, &heap, &item))
218 return NULL;
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 if (!PyList_Check(heap)) {
221 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
222 return NULL;
223 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000224
Raymond Hettinger99bf9a22015-05-11 19:25:32 -0700225 if (PyList_GET_SIZE(heap) == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 Py_INCREF(item);
227 return item;
228 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000229
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +0000230 cmp = PyObject_RichCompareBool(PyList_GET_ITEM(heap, 0), item, Py_LT);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 if (cmp == -1)
232 return NULL;
233 if (cmp == 0) {
234 Py_INCREF(item);
235 return item;
236 }
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 returnitem = PyList_GET_ITEM(heap, 0);
239 Py_INCREF(item);
240 PyList_SET_ITEM(heap, 0, item);
Raymond Hettingera032e462015-05-11 10:32:57 -0700241 if (siftup((PyListObject *)heap, 0)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 Py_DECREF(returnitem);
243 return NULL;
244 }
245 return returnitem;
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000246}
247
248PyDoc_STRVAR(heappushpop_doc,
Raymond Hettingerbd8f2902013-01-18 17:35:25 -0800249"heappushpop(heap, item) -> value. Push item on the heap, then pop and return the smallest item\n\
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000250from the heap. The combined action runs more efficiently than\n\
251heappush() followed by a separate call to heappop().");
252
Raymond Hettingerbc33e572015-05-11 10:19:03 -0700253static Py_ssize_t
254keep_top_bit(Py_ssize_t n)
255{
256 int i = 0;
257
258 while (n > 1) {
259 i += 1;
260 n >>= 1;
261 }
262 return n << i;
263}
264
265/* Cache friendly version of heapify()
266 -----------------------------------
267
268 Build-up a heap in O(n) time by performing siftup() operations
269 on nodes whose children are already heaps.
270
271 The simplest way is to sift the nodes in reverse order from
272 n//2-1 to 0 inclusive. The downside is that children may be
273 out of cache by the time their parent is reached.
274
275 A better way is to not wait for the children to go out of cache.
276 Once a sibling pair of child nodes have been sifted, immediately
277 sift their parent node (while the children are still in cache).
278
279 Both ways build child heaps before their parents, so both ways
280 do the exact same number of comparisons and produce exactly
281 the same heap. The only difference is that the traversal
282 order is optimized for cache efficiency.
283*/
284
285static PyObject *
286cache_friendly_heapify(PyObject *heap, int siftup_func(PyListObject *, Py_ssize_t))
287{
288 Py_ssize_t i, j, m, mhalf, leftmost;
289
290 m = PyList_GET_SIZE(heap) >> 1; /* index of first childless node */
291 leftmost = keep_top_bit(m + 1) - 1; /* leftmost node in row of m */
292 mhalf = m >> 1; /* parent of first childless node */
293
294 for (i = leftmost - 1 ; i >= mhalf ; i--) {
295 j = i;
296 while (1) {
297 if (siftup_func((PyListObject *)heap, j))
298 return NULL;
299 if (!(j & 1))
300 break;
301 j >>= 1;
302 }
303 }
304
305 for (i = m - 1 ; i >= leftmost ; i--) {
306 j = i;
307 while (1) {
308 if (siftup_func((PyListObject *)heap, j))
309 return NULL;
310 if (!(j & 1))
311 break;
312 j >>= 1;
313 }
314 }
315 Py_RETURN_NONE;
316}
317
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000318static PyObject *
Raymond Hettinger48f68d02014-06-14 16:43:35 -0700319heapify_internal(PyObject *heap, int siftup_func(PyListObject *, Py_ssize_t))
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 Py_ssize_t i, n;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 if (!PyList_Check(heap)) {
324 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
325 return NULL;
326 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000327
Raymond Hettingerbc33e572015-05-11 10:19:03 -0700328 /* For heaps likely to be bigger than L1 cache, we use the cache
329 friendly heapify function. For smaller heaps that fit entirely
330 in cache, we prefer the simpler algorithm with less branching.
331 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 n = PyList_GET_SIZE(heap);
Raymond Hettingerbc33e572015-05-11 10:19:03 -0700333 if (n > 10000)
334 return cache_friendly_heapify(heap, siftup_func);
335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 /* Transform bottom-up. The largest index there's any point to
337 looking at is the largest with a child index in-range, so must
338 have 2*i + 1 < n, or i < (n-1)/2. If n is even = 2*j, this is
339 (2*j-1)/2 = j-1/2 so j-1 is the largest, which is n//2 - 1. If
340 n is odd = 2*j+1, this is (2*j+1-1)/2 = j so j-1 is the largest,
341 and that's again n//2-1.
342 */
Raymond Hettinger99bf9a22015-05-11 19:25:32 -0700343 for (i = n/2 - 1 ; i >= 0 ; i--)
344 if (siftup_func((PyListObject *)heap, i))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 return NULL;
Raymond Hettinger48f68d02014-06-14 16:43:35 -0700346 Py_RETURN_NONE;
347}
348
349static PyObject *
350heapify(PyObject *self, PyObject *heap)
351{
352 return heapify_internal(heap, siftup);
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000353}
354
355PyDoc_STRVAR(heapify_doc,
356"Transform list into a heap, in-place, in O(len(heap)) time.");
357
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000358static int
Raymond Hettinger48f68d02014-06-14 16:43:35 -0700359siftdown_max(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 PyObject *newitem, *parent;
Raymond Hettinger90e93382014-05-03 18:45:54 -0700362 Py_ssize_t parentpos, size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 int cmp;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 assert(PyList_Check(heap));
Raymond Hettinger90e93382014-05-03 18:45:54 -0700366 size = PyList_GET_SIZE(heap);
367 if (pos >= size) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 PyErr_SetString(PyExc_IndexError, "index out of range");
369 return -1;
370 }
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 /* Follow the path to the root, moving parents down until finding
373 a place newitem fits. */
Raymond Hettinger871620d2014-05-03 18:36:48 -0700374 newitem = PyList_GET_ITEM(heap, pos);
Raymond Hettinger90e93382014-05-03 18:45:54 -0700375 while (pos > startpos) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 parentpos = (pos - 1) >> 1;
377 parent = PyList_GET_ITEM(heap, parentpos);
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +0000378 cmp = PyObject_RichCompareBool(parent, newitem, Py_LT);
Raymond Hettinger871620d2014-05-03 18:36:48 -0700379 if (cmp == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 return -1;
Raymond Hettinger90e93382014-05-03 18:45:54 -0700381 if (size != PyList_GET_SIZE(heap)) {
382 PyErr_SetString(PyExc_RuntimeError,
383 "list changed size during iteration");
384 return -1;
385 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 if (cmp == 0)
387 break;
Raymond Hettinger871620d2014-05-03 18:36:48 -0700388 parent = PyList_GET_ITEM(heap, parentpos);
389 newitem = PyList_GET_ITEM(heap, pos);
390 PyList_SET_ITEM(heap, parentpos, newitem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 PyList_SET_ITEM(heap, pos, parent);
392 pos = parentpos;
393 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 return 0;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000395}
396
397static int
Raymond Hettinger48f68d02014-06-14 16:43:35 -0700398siftup_max(PyListObject *heap, Py_ssize_t pos)
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000399{
Raymond Hettingerc9926082014-05-03 15:22:07 -0700400 Py_ssize_t startpos, endpos, childpos, rightpos, limit;
Raymond Hettinger871620d2014-05-03 18:36:48 -0700401 PyObject *tmp1, *tmp2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 int cmp;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 assert(PyList_Check(heap));
405 endpos = PyList_GET_SIZE(heap);
406 startpos = pos;
407 if (pos >= endpos) {
408 PyErr_SetString(PyExc_IndexError, "index out of range");
409 return -1;
410 }
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 /* Bubble up the smaller child until hitting a leaf. */
Raymond Hettingerc9926082014-05-03 15:22:07 -0700413 limit = endpos / 2; /* smallest pos that has no child */
414 while (pos < limit) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 /* Set childpos to index of smaller child. */
Raymond Hettingerc9926082014-05-03 15:22:07 -0700416 childpos = 2*pos + 1; /* leftmost child position */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 rightpos = childpos + 1;
418 if (rightpos < endpos) {
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +0000419 cmp = PyObject_RichCompareBool(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 PyList_GET_ITEM(heap, rightpos),
Raymond Hettingerdb6b62e2010-09-05 05:26:10 +0000421 PyList_GET_ITEM(heap, childpos),
422 Py_LT);
Raymond Hettinger871620d2014-05-03 18:36:48 -0700423 if (cmp == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 if (cmp == 0)
426 childpos = rightpos;
Raymond Hettinger871620d2014-05-03 18:36:48 -0700427 if (endpos != PyList_GET_SIZE(heap)) {
428 PyErr_SetString(PyExc_RuntimeError,
429 "list changed size during iteration");
430 return -1;
431 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 }
433 /* Move the smaller child up. */
Raymond Hettinger871620d2014-05-03 18:36:48 -0700434 tmp1 = PyList_GET_ITEM(heap, childpos);
435 tmp2 = PyList_GET_ITEM(heap, pos);
436 PyList_SET_ITEM(heap, childpos, tmp2);
437 PyList_SET_ITEM(heap, pos, tmp1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 pos = childpos;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 }
Raymond Hettinger871620d2014-05-03 18:36:48 -0700440 /* Bubble it up to its final resting place (by sifting its parents down). */
Raymond Hettinger48f68d02014-06-14 16:43:35 -0700441 return siftdown_max(heap, startpos, pos);
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000442}
443
444static PyObject *
Raymond Hettinger48f68d02014-06-14 16:43:35 -0700445heappop_max(PyObject *self, PyObject *heap)
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000446{
Raymond Hettinger48f68d02014-06-14 16:43:35 -0700447 return heappop_internal(heap, siftup_max);
448}
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000449
Raymond Hettinger48f68d02014-06-14 16:43:35 -0700450PyDoc_STRVAR(heappop_max_doc, "Maxheap variant of heappop.");
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000451
Raymond Hettinger48f68d02014-06-14 16:43:35 -0700452static PyObject *
453heapreplace_max(PyObject *self, PyObject *args)
454{
455 return heapreplace_internal(args, siftup_max);
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000456}
457
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700458PyDoc_STRVAR(heapreplace_max_doc, "Maxheap variant of heapreplace");
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000459
Raymond Hettinger48f68d02014-06-14 16:43:35 -0700460static PyObject *
461heapify_max(PyObject *self, PyObject *heap)
462{
463 return heapify_internal(heap, siftup_max);
464}
465
466PyDoc_STRVAR(heapify_max_doc, "Maxheap variant of heapify.");
467
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000468static PyMethodDef heapq_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 {"heappush", (PyCFunction)heappush,
470 METH_VARARGS, heappush_doc},
471 {"heappushpop", (PyCFunction)heappushpop,
472 METH_VARARGS, heappushpop_doc},
473 {"heappop", (PyCFunction)heappop,
474 METH_O, heappop_doc},
475 {"heapreplace", (PyCFunction)heapreplace,
476 METH_VARARGS, heapreplace_doc},
477 {"heapify", (PyCFunction)heapify,
478 METH_O, heapify_doc},
Raymond Hettinger48f68d02014-06-14 16:43:35 -0700479 {"_heappop_max", (PyCFunction)heappop_max,
480 METH_O, heappop_max_doc},
481 {"_heapreplace_max",(PyCFunction)heapreplace_max,
Raymond Hettinger234fb2d2014-05-11 14:21:23 -0700482 METH_VARARGS, heapreplace_max_doc},
Raymond Hettinger48f68d02014-06-14 16:43:35 -0700483 {"_heapify_max", (PyCFunction)heapify_max,
484 METH_O, heapify_max_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 {NULL, NULL} /* sentinel */
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000486};
487
488PyDoc_STRVAR(module_doc,
489"Heap queue algorithm (a.k.a. priority queue).\n\
490\n\
491Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\n\
492all k, counting elements from 0. For the sake of comparison,\n\
493non-existing elements are considered to be infinite. The interesting\n\
494property of a heap is that a[0] is always its smallest element.\n\
495\n\
496Usage:\n\
497\n\
498heap = [] # creates an empty heap\n\
499heappush(heap, item) # pushes a new item on the heap\n\
500item = heappop(heap) # pops the smallest item from the heap\n\
501item = heap[0] # smallest item on the heap without popping it\n\
502heapify(x) # transforms list into a heap, in-place, in linear time\n\
503item = heapreplace(heap, item) # pops and returns smallest item, and adds\n\
504 # new item; the heap size is unchanged\n\
505\n\
506Our API differs from textbook heap algorithms as follows:\n\
507\n\
508- We use 0-based indexing. This makes the relationship between the\n\
509 index for a node and the indexes for its children slightly less\n\
510 obvious, but is more suitable since Python uses 0-based indexing.\n\
511\n\
512- Our heappop() method returns the smallest item, not the largest.\n\
513\n\
514These two make it possible to view the heap as a regular Python list\n\
515without surprises: heap[0] is the smallest item, and heap.sort()\n\
516maintains the heap invariant!\n");
517
518
519PyDoc_STRVAR(__about__,
520"Heap queues\n\
521\n\
Neal Norwitzc1786ea2007-08-23 23:58:43 +0000522[explanation by Fran\xc3\xa7ois Pinard]\n\
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000523\n\
524Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\n\
525all k, counting elements from 0. For the sake of comparison,\n\
526non-existing elements are considered to be infinite. The interesting\n\
527property of a heap is that a[0] is always its smallest element.\n"
528"\n\
529The strange invariant above is meant to be an efficient memory\n\
530representation for a tournament. The numbers below are `k', not a[k]:\n\
531\n\
532 0\n\
533\n\
534 1 2\n\
535\n\
536 3 4 5 6\n\
537\n\
538 7 8 9 10 11 12 13 14\n\
539\n\
540 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30\n\
541\n\
542\n\
543In the tree above, each cell `k' is topping `2*k+1' and `2*k+2'. In\n\
544an usual binary tournament we see in sports, each cell is the winner\n\
545over the two cells it tops, and we can trace the winner down the tree\n\
546to see all opponents s/he had. However, in many computer applications\n\
547of such tournaments, we do not need to trace the history of a winner.\n\
548To be more memory efficient, when a winner is promoted, we try to\n\
549replace it by something else at a lower level, and the rule becomes\n\
550that a cell and the two cells it tops contain three different items,\n\
551but the top cell \"wins\" over the two topped cells.\n"
552"\n\
553If this heap invariant is protected at all time, index 0 is clearly\n\
554the overall winner. The simplest algorithmic way to remove it and\n\
555find the \"next\" winner is to move some loser (let's say cell 30 in the\n\
556diagram above) into the 0 position, and then percolate this new 0 down\n\
557the tree, exchanging values, until the invariant is re-established.\n\
558This is clearly logarithmic on the total number of items in the tree.\n\
559By iterating over all items, you get an O(n ln n) sort.\n"
560"\n\
561A nice feature of this sort is that you can efficiently insert new\n\
562items while the sort is going on, provided that the inserted items are\n\
563not \"better\" than the last 0'th element you extracted. This is\n\
564especially useful in simulation contexts, where the tree holds all\n\
565incoming events, and the \"win\" condition means the smallest scheduled\n\
566time. When an event schedule other events for execution, they are\n\
567scheduled into the future, so they can easily go into the heap. So, a\n\
568heap is a good structure for implementing schedulers (this is what I\n\
569used for my MIDI sequencer :-).\n"
570"\n\
571Various structures for implementing schedulers have been extensively\n\
572studied, and heaps are good for this, as they are reasonably speedy,\n\
573the speed is almost constant, and the worst case is not much different\n\
574than the average case. However, there are other representations which\n\
575are more efficient overall, yet the worst cases might be terrible.\n"
576"\n\
577Heaps are also very useful in big disk sorts. You most probably all\n\
578know that a big sort implies producing \"runs\" (which are pre-sorted\n\
579sequences, which size is usually related to the amount of CPU memory),\n\
580followed by a merging passes for these runs, which merging is often\n\
581very cleverly organised[1]. It is very important that the initial\n\
582sort produces the longest runs possible. Tournaments are a good way\n\
583to that. If, using all the memory available to hold a tournament, you\n\
584replace and percolate items that happen to fit the current run, you'll\n\
585produce runs which are twice the size of the memory for random input,\n\
586and much better for input fuzzily ordered.\n"
587"\n\
588Moreover, if you output the 0'th item on disk and get an input which\n\
589may not fit in the current tournament (because the value \"wins\" over\n\
590the last output value), it cannot fit in the heap, so the size of the\n\
591heap decreases. The freed memory could be cleverly reused immediately\n\
592for progressively building a second heap, which grows at exactly the\n\
593same rate the first heap is melting. When the first heap completely\n\
594vanishes, you switch heaps and start a new run. Clever and quite\n\
595effective!\n\
596\n\
597In a word, heaps are useful memory structures to know. I use them in\n\
598a few applications, and I think it is good to keep a `heap' module\n\
599around. :-)\n"
600"\n\
601--------------------\n\
602[1] The disk balancing algorithms which are current, nowadays, are\n\
603more annoying than clever, and this is a consequence of the seeking\n\
604capabilities of the disks. On devices which cannot seek, like big\n\
605tape drives, the story was quite different, and one had to be very\n\
606clever to ensure (far in advance) that each tape movement will be the\n\
607most effective possible (that is, will best participate at\n\
608\"progressing\" the merge). Some tapes were even able to read\n\
609backwards, and this was also used to avoid the rewinding time.\n\
610Believe me, real good tape sorts were quite spectacular to watch!\n\
611From all times, sorting has always been a Great Art! :-)\n");
612
Martin v. Löwis1a214512008-06-11 05:26:20 +0000613
614static struct PyModuleDef _heapqmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 PyModuleDef_HEAD_INIT,
616 "_heapq",
617 module_doc,
618 -1,
619 heapq_methods,
620 NULL,
621 NULL,
622 NULL,
623 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +0000624};
625
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000626PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000627PyInit__heapq(void)
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 PyObject *m, *about;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 m = PyModule_Create(&_heapqmodule);
632 if (m == NULL)
633 return NULL;
634 about = PyUnicode_DecodeUTF8(__about__, strlen(__about__), NULL);
635 PyModule_AddObject(m, "__about__", about);
636 return m;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000637}
638