blob: 703742e26085a730519f6ed31e0edf6c76b14ad6 [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
Martin v. Löwisad0a4622006-02-16 14:30:23 +000012_siftdown(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000013{
14 PyObject *newitem, *parent;
Martin v. Löwisad0a4622006-02-16 14:30:23 +000015 int cmp;
16 Py_ssize_t parentpos;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000017
18 assert(PyList_Check(heap));
19 if (pos >= PyList_GET_SIZE(heap)) {
20 PyErr_SetString(PyExc_IndexError, "index out of range");
21 return -1;
22 }
23
24 newitem = PyList_GET_ITEM(heap, pos);
25 Py_INCREF(newitem);
26 /* Follow the path to the root, moving parents down until finding
27 a place newitem fits. */
28 while (pos > startpos){
29 parentpos = (pos - 1) >> 1;
30 parent = PyList_GET_ITEM(heap, parentpos);
31 cmp = PyObject_RichCompareBool(parent, newitem, Py_LE);
Raymond Hettinger855d9a92004-09-28 00:03:54 +000032 if (cmp == -1) {
33 Py_DECREF(newitem);
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000034 return -1;
Raymond Hettinger855d9a92004-09-28 00:03:54 +000035 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000036 if (cmp == 1)
37 break;
38 Py_INCREF(parent);
39 Py_DECREF(PyList_GET_ITEM(heap, pos));
40 PyList_SET_ITEM(heap, pos, parent);
41 pos = parentpos;
42 }
43 Py_DECREF(PyList_GET_ITEM(heap, pos));
44 PyList_SET_ITEM(heap, pos, newitem);
45 return 0;
46}
47
48static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +000049_siftup(PyListObject *heap, Py_ssize_t pos)
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000050{
Martin v. Löwisad0a4622006-02-16 14:30:23 +000051 Py_ssize_t startpos, endpos, childpos, rightpos;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000052 int cmp;
53 PyObject *newitem, *tmp;
54
55 assert(PyList_Check(heap));
56 endpos = PyList_GET_SIZE(heap);
57 startpos = pos;
58 if (pos >= endpos) {
59 PyErr_SetString(PyExc_IndexError, "index out of range");
60 return -1;
61 }
62 newitem = PyList_GET_ITEM(heap, pos);
63 Py_INCREF(newitem);
64
65 /* Bubble up the smaller child until hitting a leaf. */
66 childpos = 2*pos + 1; /* leftmost child position */
67 while (childpos < endpos) {
68 /* Set childpos to index of smaller child. */
69 rightpos = childpos + 1;
70 if (rightpos < endpos) {
71 cmp = PyObject_RichCompareBool(
72 PyList_GET_ITEM(heap, rightpos),
73 PyList_GET_ITEM(heap, childpos),
74 Py_LE);
Raymond Hettinger855d9a92004-09-28 00:03:54 +000075 if (cmp == -1) {
76 Py_DECREF(newitem);
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000077 return -1;
Raymond Hettinger855d9a92004-09-28 00:03:54 +000078 }
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +000079 if (cmp == 1)
80 childpos = rightpos;
81 }
82 /* Move the smaller child up. */
83 tmp = PyList_GET_ITEM(heap, childpos);
84 Py_INCREF(tmp);
85 Py_DECREF(PyList_GET_ITEM(heap, pos));
86 PyList_SET_ITEM(heap, pos, tmp);
87 pos = childpos;
88 childpos = 2*pos + 1;
89 }
90
91 /* The leaf at pos is empty now. Put newitem there, and and bubble
92 it up to its final resting place (by sifting its parents down). */
93 Py_DECREF(PyList_GET_ITEM(heap, pos));
94 PyList_SET_ITEM(heap, pos, newitem);
95 return _siftdown(heap, startpos, pos);
96}
97
98static PyObject *
99heappush(PyObject *self, PyObject *args)
100{
101 PyObject *heap, *item;
102
103 if (!PyArg_UnpackTuple(args, "heappush", 2, 2, &heap, &item))
104 return NULL;
105
106 if (!PyList_Check(heap)) {
107 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
108 return NULL;
109 }
110
111 if (PyList_Append(heap, item) == -1)
112 return NULL;
113
114 if (_siftdown((PyListObject *)heap, 0, PyList_GET_SIZE(heap)-1) == -1)
115 return NULL;
116 Py_INCREF(Py_None);
117 return Py_None;
118}
119
120PyDoc_STRVAR(heappush_doc,
121"Push item onto heap, maintaining the heap invariant.");
122
123static PyObject *
124heappop(PyObject *self, PyObject *heap)
125{
126 PyObject *lastelt, *returnitem;
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000127 Py_ssize_t n;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000128
129 if (!PyList_Check(heap)) {
130 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
131 return NULL;
132 }
133
134 /* # raises appropriate IndexError if heap is empty */
135 n = PyList_GET_SIZE(heap);
136 if (n == 0) {
137 PyErr_SetString(PyExc_IndexError, "index out of range");
138 return NULL;
139 }
140
141 lastelt = PyList_GET_ITEM(heap, n-1) ;
142 Py_INCREF(lastelt);
143 PyList_SetSlice(heap, n-1, n, NULL);
144 n--;
145
146 if (!n)
147 return lastelt;
148 returnitem = PyList_GET_ITEM(heap, 0);
149 PyList_SET_ITEM(heap, 0, lastelt);
150 if (_siftup((PyListObject *)heap, 0) == -1) {
151 Py_DECREF(returnitem);
152 return NULL;
153 }
154 return returnitem;
155}
156
157PyDoc_STRVAR(heappop_doc,
158"Pop the smallest item off the heap, maintaining the heap invariant.");
159
160static PyObject *
161heapreplace(PyObject *self, PyObject *args)
162{
163 PyObject *heap, *item, *returnitem;
164
Raymond Hettinger53bdf092008-03-13 19:03:51 +0000165 if (Py_Py3kWarningFlag &&
166 PyErr_Warn(PyExc_DeprecationWarning,
167 "In 3.x, heapreplace() was removed. Use heappushpop() instead.") < 0)
168 return NULL;
169
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000170 if (!PyArg_UnpackTuple(args, "heapreplace", 2, 2, &heap, &item))
171 return NULL;
172
173 if (!PyList_Check(heap)) {
174 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
175 return NULL;
176 }
177
178 if (PyList_GET_SIZE(heap) < 1) {
179 PyErr_SetString(PyExc_IndexError, "index out of range");
180 return NULL;
181 }
182
183 returnitem = PyList_GET_ITEM(heap, 0);
184 Py_INCREF(item);
185 PyList_SET_ITEM(heap, 0, item);
186 if (_siftup((PyListObject *)heap, 0) == -1) {
187 Py_DECREF(returnitem);
188 return NULL;
189 }
190 return returnitem;
191}
192
193PyDoc_STRVAR(heapreplace_doc,
194"Pop and return the current smallest value, and add the new item.\n\
195\n\
196This is more efficient than heappop() followed by heappush(), and can be\n\
197more appropriate when using a fixed-size heap. Note that the value\n\
198returned may be larger than item! That constrains reasonable uses of\n\
Raymond Hettinger8158e842004-09-06 07:04:09 +0000199this routine unless written as part of a conditional replacement:\n\n\
200 if item > heap[0]:\n\
201 item = heapreplace(heap, item)\n");
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000202
203static PyObject *
Raymond Hettinger53bdf092008-03-13 19:03:51 +0000204heappushpop(PyObject *self, PyObject *args)
205{
206 PyObject *heap, *item, *returnitem;
207 int cmp;
208
209 if (!PyArg_UnpackTuple(args, "heappushpop", 2, 2, &heap, &item))
210 return NULL;
211
212 if (!PyList_Check(heap)) {
213 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
214 return NULL;
215 }
216
217 if (PyList_GET_SIZE(heap) < 1) {
218 Py_INCREF(item);
219 return item;
220 }
221
222 cmp = PyObject_RichCompareBool(item, PyList_GET_ITEM(heap, 0), Py_LE);
223 if (cmp == -1)
224 return NULL;
225 if (cmp == 1) {
226 Py_INCREF(item);
227 return item;
228 }
229
230 returnitem = PyList_GET_ITEM(heap, 0);
231 Py_INCREF(item);
232 PyList_SET_ITEM(heap, 0, item);
233 if (_siftup((PyListObject *)heap, 0) == -1) {
234 Py_DECREF(returnitem);
235 return NULL;
236 }
237 return returnitem;
238}
239
240PyDoc_STRVAR(heappushpop_doc,
241"Push item on the heap, then pop and return the smallest item\n\
242from the heap. The combined action runs more efficiently than\n\
243heappush() followed by a separate call to heappop().");
244
245static PyObject *
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000246heapify(PyObject *self, PyObject *heap)
247{
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000248 Py_ssize_t i, n;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000249
250 if (!PyList_Check(heap)) {
251 PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
252 return NULL;
253 }
254
255 n = PyList_GET_SIZE(heap);
256 /* Transform bottom-up. The largest index there's any point to
257 looking at is the largest with a child index in-range, so must
258 have 2*i + 1 < n, or i < (n-1)/2. If n is even = 2*j, this is
259 (2*j-1)/2 = j-1/2 so j-1 is the largest, which is n//2 - 1. If
260 n is odd = 2*j+1, this is (2*j+1-1)/2 = j so j-1 is the largest,
261 and that's again n//2-1.
262 */
263 for (i=n/2-1 ; i>=0 ; i--)
264 if(_siftup((PyListObject *)heap, i) == -1)
265 return NULL;
266 Py_INCREF(Py_None);
267 return Py_None;
268}
269
270PyDoc_STRVAR(heapify_doc,
271"Transform list into a heap, in-place, in O(len(heap)) time.");
272
Raymond Hettingerc9297662004-06-12 22:48:46 +0000273static PyObject *
274nlargest(PyObject *self, PyObject *args)
275{
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000276 PyObject *heap=NULL, *elem, *iterable, *sol, *it, *oldelem;
Thomas Wouters13870b12006-02-16 19:21:53 +0000277 Py_ssize_t i, n;
Raymond Hettingerc9297662004-06-12 22:48:46 +0000278
Thomas Wouters13870b12006-02-16 19:21:53 +0000279 if (!PyArg_ParseTuple(args, "nO:nlargest", &n, &iterable))
Raymond Hettingerc9297662004-06-12 22:48:46 +0000280 return NULL;
281
282 it = PyObject_GetIter(iterable);
283 if (it == NULL)
284 return NULL;
285
286 heap = PyList_New(0);
Raymond Hettingerde72edd2004-06-13 15:36:56 +0000287 if (heap == NULL)
Raymond Hettingerc9297662004-06-12 22:48:46 +0000288 goto fail;
289
290 for (i=0 ; i<n ; i++ ){
291 elem = PyIter_Next(it);
Raymond Hettingerde72edd2004-06-13 15:36:56 +0000292 if (elem == NULL) {
293 if (PyErr_Occurred())
294 goto fail;
295 else
296 goto sortit;
297 }
Raymond Hettingerc9297662004-06-12 22:48:46 +0000298 if (PyList_Append(heap, elem) == -1) {
299 Py_DECREF(elem);
300 goto fail;
301 }
302 Py_DECREF(elem);
303 }
304 if (PyList_GET_SIZE(heap) == 0)
305 goto sortit;
306
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000307 for (i=n/2-1 ; i>=0 ; i--)
308 if(_siftup((PyListObject *)heap, i) == -1)
309 goto fail;
Raymond Hettingerc9297662004-06-12 22:48:46 +0000310
311 sol = PyList_GET_ITEM(heap, 0);
312 while (1) {
313 elem = PyIter_Next(it);
314 if (elem == NULL) {
315 if (PyErr_Occurred())
316 goto fail;
317 else
318 goto sortit;
319 }
320 if (PyObject_RichCompareBool(elem, sol, Py_LE)) {
321 Py_DECREF(elem);
322 continue;
323 }
324 oldelem = PyList_GET_ITEM(heap, 0);
325 PyList_SET_ITEM(heap, 0, elem);
326 Py_DECREF(oldelem);
327 if (_siftup((PyListObject *)heap, 0) == -1)
328 goto fail;
329 sol = PyList_GET_ITEM(heap, 0);
330 }
331sortit:
Raymond Hettingerc9297662004-06-12 22:48:46 +0000332 if (PyList_Sort(heap) == -1)
333 goto fail;
334 if (PyList_Reverse(heap) == -1)
335 goto fail;
Raymond Hettingerde72edd2004-06-13 15:36:56 +0000336 Py_DECREF(it);
Raymond Hettingerc9297662004-06-12 22:48:46 +0000337 return heap;
338
339fail:
340 Py_DECREF(it);
341 Py_XDECREF(heap);
342 return NULL;
343}
344
345PyDoc_STRVAR(nlargest_doc,
346"Find the n largest elements in a dataset.\n\
347\n\
348Equivalent to: sorted(iterable, reverse=True)[:n]\n");
349
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000350static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000351_siftdownmax(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000352{
353 PyObject *newitem, *parent;
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000354 int cmp;
355 Py_ssize_t parentpos;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000356
357 assert(PyList_Check(heap));
358 if (pos >= PyList_GET_SIZE(heap)) {
359 PyErr_SetString(PyExc_IndexError, "index out of range");
360 return -1;
361 }
362
363 newitem = PyList_GET_ITEM(heap, pos);
364 Py_INCREF(newitem);
365 /* Follow the path to the root, moving parents down until finding
366 a place newitem fits. */
367 while (pos > startpos){
368 parentpos = (pos - 1) >> 1;
369 parent = PyList_GET_ITEM(heap, parentpos);
370 cmp = PyObject_RichCompareBool(newitem, parent, Py_LE);
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000371 if (cmp == -1) {
372 Py_DECREF(newitem);
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000373 return -1;
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000374 }
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000375 if (cmp == 1)
376 break;
377 Py_INCREF(parent);
378 Py_DECREF(PyList_GET_ITEM(heap, pos));
379 PyList_SET_ITEM(heap, pos, parent);
380 pos = parentpos;
381 }
382 Py_DECREF(PyList_GET_ITEM(heap, pos));
383 PyList_SET_ITEM(heap, pos, newitem);
384 return 0;
385}
386
387static int
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000388_siftupmax(PyListObject *heap, Py_ssize_t pos)
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000389{
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000390 Py_ssize_t startpos, endpos, childpos, rightpos;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000391 int cmp;
392 PyObject *newitem, *tmp;
393
394 assert(PyList_Check(heap));
395 endpos = PyList_GET_SIZE(heap);
396 startpos = pos;
397 if (pos >= endpos) {
398 PyErr_SetString(PyExc_IndexError, "index out of range");
399 return -1;
400 }
401 newitem = PyList_GET_ITEM(heap, pos);
402 Py_INCREF(newitem);
403
404 /* Bubble up the smaller child until hitting a leaf. */
405 childpos = 2*pos + 1; /* leftmost child position */
406 while (childpos < endpos) {
407 /* Set childpos to index of smaller child. */
408 rightpos = childpos + 1;
409 if (rightpos < endpos) {
410 cmp = PyObject_RichCompareBool(
411 PyList_GET_ITEM(heap, childpos),
412 PyList_GET_ITEM(heap, rightpos),
413 Py_LE);
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000414 if (cmp == -1) {
415 Py_DECREF(newitem);
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000416 return -1;
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000417 }
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000418 if (cmp == 1)
419 childpos = rightpos;
420 }
421 /* Move the smaller child up. */
422 tmp = PyList_GET_ITEM(heap, childpos);
423 Py_INCREF(tmp);
424 Py_DECREF(PyList_GET_ITEM(heap, pos));
425 PyList_SET_ITEM(heap, pos, tmp);
426 pos = childpos;
427 childpos = 2*pos + 1;
428 }
429
430 /* The leaf at pos is empty now. Put newitem there, and and bubble
431 it up to its final resting place (by sifting its parents down). */
432 Py_DECREF(PyList_GET_ITEM(heap, pos));
433 PyList_SET_ITEM(heap, pos, newitem);
434 return _siftdownmax(heap, startpos, pos);
435}
436
437static PyObject *
438nsmallest(PyObject *self, PyObject *args)
439{
440 PyObject *heap=NULL, *elem, *iterable, *los, *it, *oldelem;
Martin v. Löwisad0a4622006-02-16 14:30:23 +0000441 Py_ssize_t i, n;
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000442
Thomas Woutersed6254a2006-02-16 17:32:54 +0000443 if (!PyArg_ParseTuple(args, "nO:nsmallest", &n, &iterable))
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000444 return NULL;
445
446 it = PyObject_GetIter(iterable);
447 if (it == NULL)
448 return NULL;
449
450 heap = PyList_New(0);
Raymond Hettingerde72edd2004-06-13 15:36:56 +0000451 if (heap == NULL)
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000452 goto fail;
453
454 for (i=0 ; i<n ; i++ ){
455 elem = PyIter_Next(it);
Raymond Hettingerde72edd2004-06-13 15:36:56 +0000456 if (elem == NULL) {
457 if (PyErr_Occurred())
458 goto fail;
459 else
460 goto sortit;
461 }
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000462 if (PyList_Append(heap, elem) == -1) {
463 Py_DECREF(elem);
464 goto fail;
465 }
466 Py_DECREF(elem);
467 }
468 n = PyList_GET_SIZE(heap);
469 if (n == 0)
470 goto sortit;
471
472 for (i=n/2-1 ; i>=0 ; i--)
473 if(_siftupmax((PyListObject *)heap, i) == -1)
474 goto fail;
475
476 los = PyList_GET_ITEM(heap, 0);
477 while (1) {
478 elem = PyIter_Next(it);
479 if (elem == NULL) {
480 if (PyErr_Occurred())
481 goto fail;
482 else
483 goto sortit;
484 }
485 if (PyObject_RichCompareBool(los, elem, Py_LE)) {
486 Py_DECREF(elem);
487 continue;
488 }
489
490 oldelem = PyList_GET_ITEM(heap, 0);
491 PyList_SET_ITEM(heap, 0, elem);
492 Py_DECREF(oldelem);
493 if (_siftupmax((PyListObject *)heap, 0) == -1)
494 goto fail;
495 los = PyList_GET_ITEM(heap, 0);
496 }
497
498sortit:
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000499 if (PyList_Sort(heap) == -1)
500 goto fail;
Raymond Hettingerde72edd2004-06-13 15:36:56 +0000501 Py_DECREF(it);
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000502 return heap;
503
504fail:
505 Py_DECREF(it);
506 Py_XDECREF(heap);
507 return NULL;
508}
509
510PyDoc_STRVAR(nsmallest_doc,
511"Find the n smallest elements in a dataset.\n\
512\n\
513Equivalent to: sorted(iterable)[:n]\n");
514
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000515static PyMethodDef heapq_methods[] = {
516 {"heappush", (PyCFunction)heappush,
517 METH_VARARGS, heappush_doc},
Raymond Hettinger53bdf092008-03-13 19:03:51 +0000518 {"heappushpop", (PyCFunction)heappushpop,
519 METH_VARARGS, heappushpop_doc},
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000520 {"heappop", (PyCFunction)heappop,
521 METH_O, heappop_doc},
522 {"heapreplace", (PyCFunction)heapreplace,
523 METH_VARARGS, heapreplace_doc},
524 {"heapify", (PyCFunction)heapify,
525 METH_O, heapify_doc},
Raymond Hettingerc9297662004-06-12 22:48:46 +0000526 {"nlargest", (PyCFunction)nlargest,
527 METH_VARARGS, nlargest_doc},
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000528 {"nsmallest", (PyCFunction)nsmallest,
529 METH_VARARGS, nsmallest_doc},
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000530 {NULL, NULL} /* sentinel */
531};
532
533PyDoc_STRVAR(module_doc,
534"Heap queue algorithm (a.k.a. priority queue).\n\
535\n\
536Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\n\
537all k, counting elements from 0. For the sake of comparison,\n\
538non-existing elements are considered to be infinite. The interesting\n\
539property of a heap is that a[0] is always its smallest element.\n\
540\n\
541Usage:\n\
542\n\
543heap = [] # creates an empty heap\n\
544heappush(heap, item) # pushes a new item on the heap\n\
545item = heappop(heap) # pops the smallest item from the heap\n\
546item = heap[0] # smallest item on the heap without popping it\n\
547heapify(x) # transforms list into a heap, in-place, in linear time\n\
548item = heapreplace(heap, item) # pops and returns smallest item, and adds\n\
549 # new item; the heap size is unchanged\n\
550\n\
551Our API differs from textbook heap algorithms as follows:\n\
552\n\
553- We use 0-based indexing. This makes the relationship between the\n\
554 index for a node and the indexes for its children slightly less\n\
555 obvious, but is more suitable since Python uses 0-based indexing.\n\
556\n\
557- Our heappop() method returns the smallest item, not the largest.\n\
558\n\
559These two make it possible to view the heap as a regular Python list\n\
560without surprises: heap[0] is the smallest item, and heap.sort()\n\
561maintains the heap invariant!\n");
562
563
564PyDoc_STRVAR(__about__,
565"Heap queues\n\
566\n\
567[explanation by François Pinard]\n\
568\n\
569Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\n\
570all k, counting elements from 0. For the sake of comparison,\n\
571non-existing elements are considered to be infinite. The interesting\n\
572property of a heap is that a[0] is always its smallest element.\n"
573"\n\
574The strange invariant above is meant to be an efficient memory\n\
575representation for a tournament. The numbers below are `k', not a[k]:\n\
576\n\
577 0\n\
578\n\
579 1 2\n\
580\n\
581 3 4 5 6\n\
582\n\
583 7 8 9 10 11 12 13 14\n\
584\n\
585 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30\n\
586\n\
587\n\
588In the tree above, each cell `k' is topping `2*k+1' and `2*k+2'. In\n\
589an usual binary tournament we see in sports, each cell is the winner\n\
590over the two cells it tops, and we can trace the winner down the tree\n\
591to see all opponents s/he had. However, in many computer applications\n\
592of such tournaments, we do not need to trace the history of a winner.\n\
593To be more memory efficient, when a winner is promoted, we try to\n\
594replace it by something else at a lower level, and the rule becomes\n\
595that a cell and the two cells it tops contain three different items,\n\
596but the top cell \"wins\" over the two topped cells.\n"
597"\n\
598If this heap invariant is protected at all time, index 0 is clearly\n\
599the overall winner. The simplest algorithmic way to remove it and\n\
600find the \"next\" winner is to move some loser (let's say cell 30 in the\n\
601diagram above) into the 0 position, and then percolate this new 0 down\n\
602the tree, exchanging values, until the invariant is re-established.\n\
603This is clearly logarithmic on the total number of items in the tree.\n\
604By iterating over all items, you get an O(n ln n) sort.\n"
605"\n\
606A nice feature of this sort is that you can efficiently insert new\n\
607items while the sort is going on, provided that the inserted items are\n\
608not \"better\" than the last 0'th element you extracted. This is\n\
609especially useful in simulation contexts, where the tree holds all\n\
610incoming events, and the \"win\" condition means the smallest scheduled\n\
611time. When an event schedule other events for execution, they are\n\
612scheduled into the future, so they can easily go into the heap. So, a\n\
613heap is a good structure for implementing schedulers (this is what I\n\
614used for my MIDI sequencer :-).\n"
615"\n\
616Various structures for implementing schedulers have been extensively\n\
617studied, and heaps are good for this, as they are reasonably speedy,\n\
618the speed is almost constant, and the worst case is not much different\n\
619than the average case. However, there are other representations which\n\
620are more efficient overall, yet the worst cases might be terrible.\n"
621"\n\
622Heaps are also very useful in big disk sorts. You most probably all\n\
623know that a big sort implies producing \"runs\" (which are pre-sorted\n\
624sequences, which size is usually related to the amount of CPU memory),\n\
625followed by a merging passes for these runs, which merging is often\n\
626very cleverly organised[1]. It is very important that the initial\n\
627sort produces the longest runs possible. Tournaments are a good way\n\
628to that. If, using all the memory available to hold a tournament, you\n\
629replace and percolate items that happen to fit the current run, you'll\n\
630produce runs which are twice the size of the memory for random input,\n\
631and much better for input fuzzily ordered.\n"
632"\n\
633Moreover, if you output the 0'th item on disk and get an input which\n\
634may not fit in the current tournament (because the value \"wins\" over\n\
635the last output value), it cannot fit in the heap, so the size of the\n\
636heap decreases. The freed memory could be cleverly reused immediately\n\
637for progressively building a second heap, which grows at exactly the\n\
638same rate the first heap is melting. When the first heap completely\n\
639vanishes, you switch heaps and start a new run. Clever and quite\n\
640effective!\n\
641\n\
642In a word, heaps are useful memory structures to know. I use them in\n\
643a few applications, and I think it is good to keep a `heap' module\n\
644around. :-)\n"
645"\n\
646--------------------\n\
647[1] The disk balancing algorithms which are current, nowadays, are\n\
648more annoying than clever, and this is a consequence of the seeking\n\
649capabilities of the disks. On devices which cannot seek, like big\n\
650tape drives, the story was quite different, and one had to be very\n\
651clever to ensure (far in advance) that each tape movement will be the\n\
652most effective possible (that is, will best participate at\n\
653\"progressing\" the merge). Some tapes were even able to read\n\
654backwards, and this was also used to avoid the rewinding time.\n\
655Believe me, real good tape sorts were quite spectacular to watch!\n\
656From all times, sorting has always been a Great Art! :-)\n");
657
658PyMODINIT_FUNC
659init_heapq(void)
660{
661 PyObject *m;
662
663 m = Py_InitModule3("_heapq", heapq_methods, module_doc);
Neal Norwitz1ac754f2006-01-19 06:09:39 +0000664 if (m == NULL)
665 return;
Raymond Hettingerc46cb2a2004-04-19 19:06:21 +0000666 PyModule_AddObject(m, "__about__", PyString_FromString(__about__));
667}
668