]>
Commit | Line | Data |
---|---|---|
4710c53d | 1 | # -*- coding: latin-1 -*-\r |
2 | \r | |
3 | """Heap queue algorithm (a.k.a. priority queue).\r | |
4 | \r | |
5 | Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for\r | |
6 | all k, counting elements from 0. For the sake of comparison,\r | |
7 | non-existing elements are considered to be infinite. The interesting\r | |
8 | property of a heap is that a[0] is always its smallest element.\r | |
9 | \r | |
10 | Usage:\r | |
11 | \r | |
12 | heap = [] # creates an empty heap\r | |
13 | heappush(heap, item) # pushes a new item on the heap\r | |
14 | item = heappop(heap) # pops the smallest item from the heap\r | |
15 | item = heap[0] # smallest item on the heap without popping it\r | |
16 | heapify(x) # transforms list into a heap, in-place, in linear time\r | |
17 | item = heapreplace(heap, item) # pops and returns smallest item, and adds\r | |
18 | # new item; the heap size is unchanged\r | |
19 | \r | |
20 | Our API differs from textbook heap algorithms as follows:\r | |
21 | \r | |
22 | - We use 0-based indexing. This makes the relationship between the\r | |
23 | index for a node and the indexes for its children slightly less\r | |
24 | obvious, but is more suitable since Python uses 0-based indexing.\r | |
25 | \r | |
26 | - Our heappop() method returns the smallest item, not the largest.\r | |
27 | \r | |
28 | These two make it possible to view the heap as a regular Python list\r | |
29 | without surprises: heap[0] is the smallest item, and heap.sort()\r | |
30 | maintains the heap invariant!\r | |
31 | """\r | |
32 | \r | |
33 | # Original code by Kevin O'Connor, augmented by Tim Peters and Raymond Hettinger\r | |
34 | \r | |
35 | __about__ = """Heap queues\r | |
36 | \r | |
37 |