|
ADS
Algorithms and Data Structures
|
The headers of include/ADS/priority realize the PRIORITYQUEUE of section 10.1 of the book, on the lists, the trees and the heaps that the book compares, and on several structures beyond it: the Fibonacci heap that section 11.5 names for the shortest paths, the pairing heap, the heaps of plain items without handles, the monotone queues of integer keys, the double-ended queues, and the structures that merge \( k \) sorted sequences, the tree of losers among them, on which the sequence heap of Sanders rests. This page collects what the headers take for granted: the definitions and the notation shared by all of them (see Definitions and notation), the realizations and the costs of their operations (see Realizations and their costs), and, for each family of structures, the invariant on which its correctness rests and the argument behind its bounds (from Heaps to Merging sequences and the cache), and the events by which the indexed heap tells its changes (see The events of the indexed heap). The pseudocode of each operation is instead on the page of its header, in the comment of its function, together with the section of the book, or the paper, that it follows.
A priority queue holds a multiset of \( n \) items, each \( x \) with a priority \( p( x ) \) taken from a totally ordered set, and offers insert( x , p ), which adds an item, min(), which reads an item of least priority, and deleteMin(), which removes it; the PRIORITYQUEUE of the book (section 10.1, the concept PriorityQueue of PriorityQueue.h) has also decrease( y , p ), which lowers to \( p \) the priority of the item that the handle \( y \) names, the handle being what insert() gave for it (a cell, a node, an index). The items of equal priority leave in no given order unless a header says otherwise. A queue without handles (DaryHeap, MinMaxHeap, SequenceHeap, the monotone queues) has no decrease(): an item whose priority improves is pushed again, and its stale copy is skipped when it comes out (the lazy deletion), which costs \( O( m ) \) items in the queue instead of \( O( n ) \) for \( m \) decreases. Several queues order their items by a predicate better( a , b ), true if \( a \) must come out before \( b \), with std::less giving the least item first.
A queue is monotone if the priorities pushed are never smaller than the last one extracted, \( \ell \); Dijkstra's algorithm with nonnegative costs is monotone, since the distance of a node extracted is not smaller than that of the node extracted before it, and so is the simulation of discrete events. The monotone queues of integer keys use this property to find the minimum without comparisons.
| Symbol | Meaning |
|---|---|
| \( n \), \( p( x ) \) | the number of items in the queue, and the priority (or key) of the item \( x \) |
| \( d \), \( D \) | the arity of a heap, the number of children of each node, 2 for the binary heap of the book |
| \( h \) | the height of a heap, the number of its levels less one |
| \( \ell \) | the last key extracted from a monotone queue, below which no key is pushed |
| \( W \), \( B \), \( C \) | the bits of a key of a radix heap (the buckets of the window of the queue of Dial), the bits of one of its digits, and the width of the band \( [ \ell , \ell + C ] \) of the keys pushed |
| \( k \) | the number of sequences merged, or of players of a tree of losers |
| \( M \), \( B \) | in the model of the cache, the items that the cache holds and those of a block, i.e., of a line or of a page |
| \( F_k \), \( \phi \) | the \( k \)-th number of Fibonacci, \( F_0 = 0 \), \( F_1 = 1 \), and the golden ratio \( \phi = ( 1 + \sqrt{5} ) / 2 \) |
A cost is amortized when it holds for the average of any sequence of operations from the empty queue, though a single operation may cost more; the bounds of the Fibonacci, pairing and radix heaps, and those of the queues that sort a run of removals, are of this kind, and they are proved by a potential \( \Phi \geq 0 \), zero on the empty queue, whose increase pays for the cheap operations and whose decrease pays for the dear ones.
The library has three realizations of the PRIORITYQUEUE of the book, which section 10.1 compares, and several beyond it, which differ in the bounds, in the operations, and in the way they use the memory.
| Realization | min() | insert() | deleteMin() | decrease() |
|---|---|---|---|---|
| ListPriorityQueue, sorted | \( O( 1 ) \) | \( O( n ) \) | \( O( 1 ) \) | \( O( n ) \) |
| ListPriorityQueue, unsorted | \( O( n ) \) | \( O( 1 ) \) | \( O( n ) \) | \( O( 1 ) \) |
| TreePriorityQueue | \( O( \log n ) \) | \( O( \log n ) \) | \( O( \log n ) \) | \( O( \log n ) \) |
| HeapPriorityQueue, LinkedHeapPriorityQueue, IndexedDaryHeap | \( O( 1 ) \) | \( O( \log_d n ) \) | \( O( d \log_d n ) \) | \( O( \log_d n ) \) (not on the heap with pointers) |
| IndexedHeapPair (the least key and the least bound) | \( O( 1 ) \), both | \( O( \log_d n ) \) | \( O( d \log_d n ) \) | \( O( d \log_d n ) \), with the bound |
| FibonacciHeapPriorityQueue | \( O( 1 ) \) | \( O( 1 ) \) | \( O( \log n )^* \) | \( O( 1 )^* \) |
| PairingHeap | \( O( 1 ) \) | \( O( 1 )^* \) | \( O( \log n )^* \) | \( O( 2^{2 \sqrt{\log \log n}} )^* \) |
| DaryHeap, SequenceHeap | \( O( 1 ) \) | \( O( \log n ) \), \( ^* \) on the sequence heap | \( O( \log n ) \), \( ^* \) on the sequence heap | none |
| RadixHeap, DialQueue, BucketQueue (monotone, integer keys) | as deleteMin() | \( O( 1 ) \) | \( O( W / B + 2^B W / ( 64 B ) )^* \), \( O( 1 + W / 64 ) \) and \( O( 1 )^* \) in a band of width \( C < W \) | none |
| MinMaxHeap, IntervalHeap (double-ended) | \( O( 1 ) \), and the maximum as well | \( O( \log n ) \) | \( O( \log n )^* \), and the maximum as well | none |
The list sorted pays at the insertion the scan that finds the place of the item, and the unsorted one pays it at the extraction, which scans for the minimum; the list is usually preferable only for a few items, or when one of the two operations is much rarer than the other. The Red-Black tree keeps the pairs \( ( p( x ) , i ) \), \( i \) the number of insertion, which makes the keys distinct, and its height \( O( \log n ) \) bounds every operation; it is the realization of the book that also visits the items in order. The heap of the book has the same bounds with better constants, and is usually preferable: its items lie in a vector, the minimum is at its root, and only one path from the root is walked by each operation (see Heaps). The Fibonacci and the pairing heaps lower the cost of decrease(), which matters when the decreases outnumber the extractions, as in Dijkstra's and Prim's algorithms on dense graphs (see Fibonacci and pairing heaps). The monotone queues and the merges are described in Monotone queues of integer keys and Merging sequences and the cache.
A heap is a tree in which each node has a priority not smaller than that of its parent; hence its root holds a minimum, and min() costs \( O( 1 ) \). The heap of section 10.1.3 (HeapPriorityQueue.h) is a \( d \)-ary tree full but for the rightmost leaves of its last level, stored by levels in a vector \( H[ 0 .. n - 1 ] \), so that the children of the place \( i \) are \( d i + 1 , \ldots , d i + d \) and its parent is \( \lfloor ( i - 1 ) / d \rfloor \), with no pointer stored.
Lemma 1 (the height of a heap). A \( d \)-ary heap of \( n \ge 1 \) items has
\[ h = \lceil \log_d ( ( d - 1 ) n + 1 ) \rceil - 1 \tag{1} \]
levels below its root.
Indeed, its first \( h \) levels are full and hold \( 1 + d + \cdots + d^{h-1} = ( d^h - 1 ) / ( d - 1 ) \) items, fewer than \( n \), while the full levels up to the last would hold \( ( d^{h+1} - 1 ) / ( d - 1 ) \ge n \); taking the logarithms gives (1), i.e., \( h = \Theta( \log_d n ) \).
insert() puts the new item in the first free place, a leaf, and moves it up while it is smaller than its parent; the heap is violated only between the item and its parent, and each swap moves the violation one level up, so that at most \( h \) swaps, of one comparison each, restore the order. decrease() does the same from the place of the item, which the item keeps up to date at each swap, so that the handle finds it in \( O( 1 ) \). deleteMin() moves the last leaf into the root and down (minHeapRestore() of the book), swapping it with its smallest child while that child is smaller; the violation now lies between the item and its children, and each level costs \( d \) comparisons, i.e., \( O( d \log_d n ) \) in all.
With \( m \) decreases and \( n \) extractions, as in Dijkstra's algorithm, a \( d \)-ary heap costs
\[ O( m \log_d n + n d \log_d n ) , \tag{2} \]
which is least for \( d \) near \( \max\{ 2 , m / n \} \), i.e., \( O( m \log_{2 + m / n} n ) \) (Johnson); on the dense graphs this is \( O( m ) \), as the Fibonacci heap gives. In practice \( d = 4 \) is usually preferable even when (2) would ask for \( d = 2 \), since the four children of a node lie in one line of the cache and the heap is half as deep (LaMarca and Ladner; Larkin, Sen and Tarjan): this is the default of DaryHeap and of IndexedDaryHeap, which keep the keys in the vector itself, so that a comparison never follows a pointer, and replace the handles by plain items (DaryHeap) or by the vector of the places of the ids \( [ 0 , n ) \) (IndexedDaryHeap). The walk down of deleteMin() compares the item carried down with the best child at each level; the walk from the bottom up of Floyd and Wegener (the BottomUp of DaryHeap) moves instead the hole of the root down to a leaf by the best children, \( d - 1 \) comparisons per level, and then the item up from there. The item carried down is the last leaf, which usually belongs near the bottom, so that the climb from the leaf is short and the walk saves about one comparison per level; it loses when the item would stop halfway.
A search that prunes or reorders its frontier needs more than decrease(): the removal of any item and the raise of its key. IndexedDaryHeap raises the key of an id by the walk down of pop() from its place, and removes an id by moving the last item into its place and then up or down. A search that numbers its nodes as it generates them also needs the range of the ids to grow with the heap: grow( n ) extends the vector of the places, at least doubling it when it is full, so that a new id costs \( O( 1 ) \) amortized and the items stay where they are.
Lemma 2 (the hole of a removal). Let the item at the place \( i \) of a heap be removed and the last item \( x \) be put in its place. If \( x \) is smaller than the parent of \( i \), the walk up from \( i \) restores the heap, and otherwise the walk down does; one walk alone is needed, and the removal costs \( O( d \log_d n ) \).
Indeed, the items below \( i \) are not smaller than the item removed, which is not smaller than the parent of \( i \); if \( x \) is smaller than that parent, it is smaller than all of them, and the heap is violated only between \( x \) and its ancestors, which the walk up mends as in insert(). Otherwise \( x \) is not smaller than its parent, the heap is violated only between \( x \) and its children (\( x \) may come from another subtree, where it was larger than the items below \( i \)), and the walk down mends it as in deleteMin().
The searches that select a node by one key and must know the least of a second one over the whole frontier (a bounded suboptimal search, which expands by an inflated cost or by the distance to the goal and stops by the least lower bound \( f_{\mathrm{min}} \); a branch and bound by best estimate, which prunes by the least bound of the open nodes) keep the ids in two such heaps, by the key and by the bound (IndexedHeapPair): the two minima are read in \( O( 1 ) \), and a pop() by the key removes the id from the heap of the bounds by Lemma 2, so that every operation costs two walks, \( O( d \log_d n ) \). A heap of the bounds with lazy deletion, in which the ids popped stay until they reach its top, saves the second walk of pop() but keeps up to \( O( m ) \) stale entries for \( m \) operations and needs a stamp per entry to tell the copies of an id pushed again; the pair keeps exactly \( n \) entries in each heap and changes the bound of an id where it is.
An ordered frontier, read in order from its least item and changed anywhere (a parallel search that looks among the first items for one it may expand, or a list of free blocks kept by their least key), is not a heap but an ordered dictionary with iterators: of the trees of ADS, BTreeMap has the iteration from the least key and the removal by an iterator, erase( it ), which gives the item after it, besides lowerBound(), along \( O( \log n ) \) nodes of a few lines of cache (see B-trees), while SkipList, BTree and AVLTree remove by the key alone. A frontier that is only popped is better kept in a heap, whose items need no order beyond the minimum.
The heap with pointers of LinkedHeapPriorityQueue.h keeps the same shape on nodes linked to their parent and children. The node \( k \) of the numbering by levels from 1 is reached from the root by the bits of \( k \) after the leading one, 0 to the left and 1 to the right, since the children of the node \( k \) are \( 2 k \) and \( 2 k + 1 \); thus the place of the next leaf and that of the last one are found in \( O( \log n ) \), and the bounds are those of the vector, with \( d = 2 \).
A Fibonacci heap (FibonacciHeapPriorityQueue.h) is a collection of heap ordered trees, whose roots lie in a circular list with a pointer to the least of them. insert() adds a tree of one node to the list, and decrease() cuts the node from its parent if it became smaller than it, making it a root; a node that loses a second child since it became a child is cut in turn (the cascading cut, a mark recording the first loss). deleteMin() is the only operation that tidies the heap: it moves the children of the minimum among the roots and then consolidates them, linking two roots of equal degree, the larger under the smaller, until the degrees of the roots differ. With \( t \) the number of trees and \( \mu \) the number of marked nodes, the potential
\[ \Phi = t + 2 \mu \tag{3} \]
gives the bounds of Fredman and Tarjan. insert() raises \( \Phi \) by 1 and costs \( O( 1 ) \). A decrease() that makes \( c \) cuts costs \( O( c ) \), adds \( c \) trees and removes the marks of at least \( c - 1 \) nodes, marking one more; hence \( \Phi \) changes by at most \( c + 2 ( 2 - c ) = 4 - c \), and the amortized cost is \( O( 1 ) \). The consolidation of \( t \) roots costs \( O( t + D ) \), with \( D \) the largest degree, and leaves at most \( D + 1 \) trees; hence deleteMin() costs \( O( D ) \) amortized, and the next lemma bounds \( D \).
Lemma 3 (the degrees of a Fibonacci heap). A node of degree \( k \) has at least
\[ F_{k+2} \ge \phi^k \tag{4} \]
descendants, itself included; hence \( D \le \log_\phi n \).
In fact, take the children of a node \( x \) in the order in which they were linked to it. When the \( i \)-th child was linked, \( x \) had at least \( i - 1 \) children, and the child had the same degree, since only the roots of equal degree are linked; it has lost at most one child since then, or it would have been cut, so that its degree is at least \( i - 2 \). By induction on the degree, the sizes \( s_k \) satisfy \( s_k \ge 2 + \sum_{i=2}^{k} s_{i-2} \), whose solution is \( F_{k+2} \), and \( F_{k+2} \ge \phi^k \) by the recurrence of the numbers of Fibonacci. Thus the heap gives \( O( m + n \log n ) \) for the shortest paths of Dijkstra (see Shortest paths), against the \( O( m \log n ) \) of a binary heap; in practice its constants are larger, and a heap in a vector is usually faster but on large and dense graphs.
A pairing heap (PairingHeap.h) is one heap ordered tree, whose nodes keep their leftmost child and their siblings. Two trees are linked by making the root of larger priority the leftmost child of the other one, in one comparison. insert() links a tree of one node with the root, and decrease() cuts the subtree of the node and links it with the root; deleteMin() removes the root and joins its children by two passes, the first linking them in pairs from the left and the second linking the results from the right. No balance is kept, and the analysis is that of a self-adjusting structure: deleteMin() costs \( O( \log n ) \) amortized (Fredman, Sedgewick, Sleator and Tarjan), insert() \( O( 1 ) \) (Iacono) and decrease() \( O( 2^{2 \sqrt{\log \log n}} ) \) (Pettie), and Fredman proved that \( \Omega( \log \log n ) \) amortized is needed by decrease() in this family of heaps, against the \( O( 1 ) \) of the Fibonacci heap. In the experiments the pairing heap is nevertheless faster than the Fibonacci heap (Stasko and Vitter; Larkin, Sen and Tarjan). The auxiliary two-pass variant of Stasko and Vitter (the Aux of PairingHeap) keeps the trees of insert() and decrease() in a list beside the root, which deleteMin() joins by the multipass pairing, i.e., linking the trees in pairs from the front of a queue and putting the result at its back, until one tree is left; it pays when the insertions outnumber the extractions.
The pairing heap removes any node by the delete of Fredman et al.: the node is cut from its siblings, its children are joined by the two passes of deleteMin(), and the tree that results is linked with the root (or put in the list beside it with Aux), so that erase() costs as a deleteMin() on the subtree of the node, \( O( \log n ) \) amortized, the potential of the analysis counting the trees joined there as it counts those of the root. A raise of the priority cannot leave the node where it is, since its children may now be smaller than it: the node is taken out in the same way, its children joined in its place, and inserted again alone, with the same handle (increase()), at the same cost.
On a monotone queue whose keys are integers, the minimum can be found by the position of the keys rather than by comparisons. The queue of Dial (DialQueue.h) keeps the items with key \( k \) in the bucket \( k \bmod W \) of a circular window of \( W \) buckets. If every key pushed lies in \( [ \ell , \ell + C ] \) with \( C < W \), the keys in the queue lie in \( [ \ell , \ell + W ) \), and two of them in one bucket are equal; hence the minimum is in the first bucket in use from that of \( \ell \) around the circle, found by a scan of a bit per bucket, i.e., of \( W / 64 \) words. A key beyond the window goes to a radix heap, from which the items move into the window when the window reaches them.
The radix heap of Ahuja, Mehlhorn, Orlin and Tarjan (RadixHeap.h) splits a key \( x \) of \( W \) bits into digits of \( B \) bits and puts it in the bucket of index
\[ 2^B r + x_r , \qquad r \text{ the digit of the highest bit in which } x \text{ and } \ell \text{ differ} , \tag{5} \]
\( x_r \) the digit \( r \) of \( x \), and \( r = 0 \) if \( x = \ell \). A key pushed must not be smaller than any key extracted or read, which the heap checks against the largest of them; the buckets need only \( x \ge \ell \), and \( \ell \) may lag behind that key, since extractBelow() extracts whole buckets without moving \( \ell \).
Lemma 4 (the order of the buckets). With \( x , y \ge \ell \), if the bucket of \( x \) has a smaller index than that of \( y \), then \( x < y \); and the keys of a bucket of the row \( r = 0 \) are all equal.
Indeed, \( x \) agrees with \( \ell \) above its digit \( r \), and its digit \( r \) is larger than that of \( \ell \) when \( r > 0 \), since \( x > \ell \). If \( y \) lies in a higher row \( r' > r \), then \( x \) agrees with \( \ell \) on the digit \( r' \) and above, while \( y \) agrees with \( \ell \) above \( r' \) and exceeds it on the digit \( r' \); hence \( y > x \). If \( y \) lies in the same row, both agree with \( \ell \) above the digit \( r \), and the digits \( r \), i.e., the indices of the buckets, decide. In the row 0, \( x \) and \( \ell \) differ only in the last digit, which is the index of the bucket.
Hence the minimum is in the first bucket in use, which a mask of the buckets finds by its lowest bit. If that bucket lies in a row \( r > 0 \), its least key becomes the new \( \ell \), and its items move to the buckets that (5) gives for it, all in rows below \( r \), while the other buckets keep their items. An item thus only moves to lower rows, at most \( \lceil W / B \rceil - 1 \) times, and with the potential \( \Phi = \sum_x \mathrm{row}( x ) \) a push costs \( O( W / B ) \) amortized and an extraction \( O( 2^B W / ( 64 B ) ) \), the scan of the mask, i.e., \( O( 1 ) \) per push and \( O( W / B + 2^B W / ( 64 B ) ) \) per extraction when every item pushed is extracted. A key of a band of width \( C \) above \( \ell \) may still lie in a high row, since a carry changes high bits (\( 7 \) and \( 8 \) differ in the bit 3); however, after its first move the key and every later \( \ell \) lie in one interval \( [ Q , Q + C ) \), \( Q \) a multiple of \( 2^{B r} \) and \( r \) the row it left, so that its row is then at most \( \lceil \log_2 C \rceil / B \): an item moves at most \( 1 + \lceil \log_2 C \rceil / B \) times, and with \( B = 1 \) an extraction costs \( O( \log C + W / 64 ) \) amortized.
The two levels of BucketQueue.h apply the scan of Dial to two keys, the first \( f \) of the order and the second \( g \) that breaks its ties toward the largest, which is the order of the search A* (least \( f \), ties toward the deeper nodes). The outer level is a vector of layers indexed by \( f \), scanned forward from the least \( f \) in use; the scan only moves forward between two pushes of a smaller \( f \), and with keys bounded by \( C \) it costs \( O( 1 ) \) amortized per operation. A layer, the items of one \( f \), keeps a LIFO list per \( g \), in one of two ways. The lists of \( g < D \) (\( D = 256 \)) are dense, an array of heads indexed by \( g \) and scanned backward from a bound that only moves down between two pushes of a larger \( g \). The lists of \( g \ge D \) are runs while they are at most \( R = 64 \): a vector of pairs \( ( g , h ) \), \( h \) the head of the list of \( g \), sorted by increasing \( g \), whose last pair is the top of the layer. A push of a \( g \) larger than the last appends a run, a push of the last \( g \) prepends to its list, and any other push finds its place by a binary search and shifts the larger runs by one place. A push of any \( g \ge D \), new or not, into a layer of \( R \) runs turns the layer dense on all its \( g \): the heads of the runs, not the items, move into an array as long as the largest \( g \), and the layer stays dense until it empties, when it frees the array and is sparse again.
Lemma 5 (the cost of a layer). Between two times at which a layer is empty, let it receive \( m \) pushes and as many pops, and let \( u \) be the sum of the amounts by which the pushes raise the bound of the scan of the dense lists. The operations cost \( O( m + u ) \) if no push of a \( g \ge D \) meets \( R \) runs, and \( O( m + u + G ) \) otherwise, \( G \) the largest \( g \) pushed into the layer; when all the pushes come before all the pops, \( u \) is below \( D \) in the first case and at most \( G \) in the second, while with pushes and pops interleaved it may reach \( \Theta( m D ) \).
Indeed, a push to the runs costs \( O( 1 ) \) when its \( g \) is not below the last, and \( O( \log R + R ) = O( 1 ) \) otherwise, since \( R \) is a constant and the shift moves at most \( R \) runs, while a pop takes the head of the last run in \( O( 1 ) \). A step of the scan lowers the bound by one, the bound is never negative and only a push raises it, and hence the steps of the scan are at most \( u \). The conversion and the array that follows it cost \( \Theta( G ) \), and the conversion needs \( R \) runs, i.e., more than \( R \) pushes. When the pushes come first, the bound grows from 0 to the largest \( g \) of the dense lists while they last; with \( m / 2 \) items of \( g = 0 \) pushed first, each round of a push of \( g = D - 1 \) and two pops costs instead a scan of \( D - 1 \) steps. A dense array alone would instead cost \( \Theta( G ) \) at each filling, even of one item, which is the case of the least layer of a search whose nodes come in small batches; a binary heap per layer would cost \( O( \log m ) \) per operation, more than the dense lists on a layer of many items, and would lose the order of the lists, which the view of the standard interface walks.
The order among the items of one \( f \) is a policy of the queue: with LeastSecondKey the least \( g \) comes first, i.e., the order of the pairs \( ( f , g ) \) is lexicographic, that of the keys \( ( k_1 , k_2 ) \) of LPA* (Koenig, Likhachev and Furcy). The structure is then the mirror image of the one above: the bound of the dense lists is scanned forward and moves only up between two pushes of a smaller \( g \), the runs are kept by decreasing \( g \), so that the last is still the top, and the dense lists of a layer, all of \( g < D \) while it has runs, come before its runs. The argument of Lemma 5 holds word for word with the directions exchanged.
The order is the same in both ways (LIFO inside a list, the lists by \( g \)), since the conversion moves the heads and not the items. The items lie in one vector of cells, each with the index of the next cell of its list, and the cells freed by the pops form a list that the pushes take from first, so that no operation calls the allocator once the vector has grown to the largest size of the queue; the vectors of runs of the layers that empty are kept for the next layers that need one. The memory is
\[ O\Bigl( n + F + \sum_f H_f + R L \Bigr) \text{ words,} \]
\( F \) the largest \( f \) pushed, \( H_f \) the heads of the layer \( f \) while it is in use (at most \( D \) if it is sparse, its largest \( g \) if it is dense) and \( L \) the most layers that had runs at the same time. There is no decrease(): as in the lazy deletion of A*, an item whose key improves is pushed again, and the caller skips the stale copies when they come out.
A double-ended queue has both the best and the worst item at hand (MinMaxHeap.h). The min-max heap of Atkinson, Sack, Santoro and Strothotte is a binary heap in a vector whose levels alternate: a node of an even level, the root's, is not worse than any item of its subtree, and one of an odd level is not better. The best item is then the root and the worst the worse of its children. An item pushed is swapped at most once with its parent, to reach a level of the right kind, and then moved up by its grandparents; an item moved down from the root (or from the child of the worst) is compared with the up to 2 children and 4 grandchildren, and swapped with its parent of the other kind when it lands on a grandchild. Both walks cost \( O( \log n ) \).
The interval heap of van Leeuwen and Wood keeps the items two by two in the nodes of a complete binary tree, each node an interval \( [ \mathit{lo} , \mathit{hi} ] \) with
\[ \mathit{lo}( q ) \preceq \mathit{lo}( j ) \preceq \mathit{hi}( j ) \preceq \mathit{hi}( q ) , \qquad q \text{ the parent of } j , \tag{6} \]
\( \preceq \) the order of better(). Hence the \( \mathit{lo} \) of the nodes form a heap for the best item and the \( \mathit{hi} \) a heap for the worst, and a walk of either kind costs two comparisons per level on a tree of half the height of a binary heap, with the two items of a node in one line of the cache. In both heaps, a run of removals with no push, as long as an eighth of the items, sorts the items once in \( O( n \log n ) \) (or by the radix sort, \( O( n ) \), on numbers), so that the rest of the run takes them from the two ends of the sorted array in \( O( 1 ) \) each; the next push rebuilds a heap in \( O( n ) \). The run pays for both, since it holds \( \Omega( n ) \) removals, and the amortized cost of a removal stays \( O( \log n ) \).
The merge of \( k \) sorted sequences extracts at each step the least of their first items; a heap of the \( k \) first items does it with a deleteMin() and an insert(), up to \( 2 \log_2 k \) comparisons. The tree of losers of a tournament (LoserTree.h, Knuth 5.4.1) does better: the \( k \) sequences are the leaves of a complete binary tree, each internal node keeps the loser of the match played there, and the root the overall winner. When the winner takes its next item, only the matches on the path from its leaf to the root change, and each is played against the loser stored there, one comparison per level; hence a merge of \( n \) items costs at most
\[ n \lceil \log_2 k \rceil + k \tag{7} \]
comparisons, the term \( k \) for the construction, which plays the \( k - 1 \) matches once. Equal keys are won by the lower index, so that the merge is stable. FlatLoserTree of MultiwayMerge.h keeps the key of each loser in its node, so that a replay reads only the array of the tree, and makes the matches and the swaps by masks, since a branch would be mispredicted half of the time on random keys. The funnel of multiwayMerge() (the cache-oblivious \( k \)-merger of Frigo, Leiserson, Prokop and Ramachandran, made of binary mergers as Brodal, Fagerberg and Vinther engineered it) is a tree of binary mergers with a buffer at each node, filled lazily when it runs out; each item climbs \( \lceil \log_2 k \rceil \) mergers, \( O( n \log k ) \) in all, and the steps of a merge of two check no end and make no jump.
In the model of the cache, with \( M \) items in the cache and \( B \) in a block, a heap of \( n \gg M \) items misses the cache at almost every level of a walk, i.e., \( \Theta( \log ( n / M ) ) \) times per operation. The sequence heap of Sanders (SequenceHeap.h) keeps instead the items in sorted sequences, merged in large batches: the new items go to an insertion heap of \( m = \Theta( M ) \) items, which, when full, is sorted into a sequence of the group 1; the group \( i \) holds up to \( k = \Theta( M / B ) \) sequences of at most \( m k^{i-1} \) items, and when it is full its sequences are merged into one of the group \( i + 1 \); the best items wait in a deletion buffer, refilled by merging the buffers of the groups. Each item is merged once per group, by a tree of losers of \( k \) sequences, and the sequences are read and written in order; hence the operations cost \( O( \log n ) \) amortized comparisons, as a binary heap, and
\[ O\left( \frac{1}{B} \log_{M / B} \frac{n}{M} \right) \tag{8} \]
amortized misses per item (Sanders, theorem 1), i.e., the bound of the sorting in external memory divided by the items. The pushes into an empty sequence heap go to a bulk in the order of arrival, which the incremental quicksort of Paredes and Navarro sorts only as far as the extractions need, \( O( n + k \log k ) \) expected for the \( k \) best items of \( n \).
The BinaryHeap of section 10.1 of Morin's book is DaryHeap with \( D = 2 \) (DaryHeap.h), its array in the order of Eytzinger: the children of the place \( i \) are \( D i + 1 , \ldots , D i + D \) and its parent is \( \lfloor ( i - 1 ) / D \rfloor \), since the places before the first child of \( i \) are the root and the \( D \) children of each of the \( i \) places before \( i \) (exercise 10.4). A push moves up \( \log_D n \) levels with one comparison each, a pop moves down as many levels with \( D \) comparisons each, \( D - 1 \) among the children and one with the item, so that the pop makes \( D \log_D n = ( D / \log_2 D ) \log_2 n \) comparisons, the least for \( D = 3 \) and as many for \( D = 4 \) as for \( D = 2 \), with half the levels and the four children consecutive in the array (exercise 10.5), in at most two lines of cache. The insertions of 7 and 3 and the removals of 6 and 8 of exercises 10.1 and 10.2 give the arrays that the test ods10.1.binary-heap checks, from the heap of figures 10.2 and 10.3.
erase( i ) removes the item of a place in \( O( D \log_D n ) \): the last item takes its place and moves up, if it is better than the parent there, or down otherwise, the order holding above and below it in either case (exercise 10.3). It is of little use since the places of the items change at every operation and a caller has no handle to follow them, so that it must search the place first, in \( O( n ) \); IndexedDaryHeap keeps the place of each item instead. The second best item is the best child of the root, \( O( D ) \), and in the randomized meldable heap the smaller child of the root, \( O( 1 ) \) (exercise 10.9). The \( k \) best items are the first \( k \) that a heap \( Q \) of places gives, which starts from the root and receives the children of each place it gives: each item of the answer has its parent in the answer before it, so that \( Q \) holds the best item not yet given, and it never holds more than \( k ( D - 1 ) + 1 \) places, \( O( k D \log k ) \) time (exercise 10.10). The same heap of the first items of \( k \) sorted lists, the list of the item given putting its next one, merges them in \( O( n \log k ) \) (exercise 10.11, in the test ods.ex10.11.k-way-merge; multiwayMerge() and the trees of losers of MultiwayMerge.h do it with fewer comparisons per item).
Lemma 6 (the random walk of the meldable heap). In a binary tree of \( n \) nodes, the walk from the root that goes to either child with probability \( 1 / 2 \) until it leaves the tree has an expected length of at most \( \log_2( n + 1 ) \) (Lemma 10.1 of Morin's book).
Indeed, by induction on \( n \): with \( n_1 + n_2 = n - 1 \) nodes in the two subtrees, the expected length is at most \( 1 + ( \log_2( n_1 + 1 ) + \log_2( n_2 + 1 ) ) / 2 \le 1 + \log_2( ( n + 1 ) / 2 ) = \log_2( n + 1 ) \), by the concavity of the logarithm. The merge of the randomized meldable heap of Gambin and Malinowski (MeldableHeap.h) follows such a walk in each of the two heaps, the smaller root staying on top and the other heap going down a child chosen by a coin, so that it takes \( O( \log n_1 + \log n_2 ) \) expected time whatever the shapes, and so do the push, the pop, the meld of two heaps and the removal of the node of a handle, which merges the two subtrees of the node and hangs the result where the node was, the order holding between its parent and every node below it (exercise 10.8). The coins of exercises 10.6 and 10.7 are those of a seeded generator in the test ods10.2.meldable-heap, since the shape of the heap of figure 10.4 after the operations depends on them.
IndexedDaryHeap tells its changes through a subject policy of Modification.h (see Typed modifications): \( \mathrm{Inserted} \), \( \mathrm{Erased} \) and \( \mathrm{KeyChanged} \) of the ids, which are stable handles, and, only for an observer that wants them, the moves of the items in the vector as \( \mathrm{Relocated}( p , q ) \), the exchange of the contents of the places \( p \) and \( q \), an empty place included. The event of the item comes first: the new item at the place \( s \) after the last, the key changed where the item is, the place of an erased item left empty.
Lemma 7 (the exchanges of a heap). Let an observer keep a copy \( M \) of the vector of the ids, placing an inserted id at the place \( s \), emptying the place of an erased one, and exchanging \( M[ p ] \) and \( M[ q ] \) at each \( \mathrm{Relocated}( p , q ) \) (dropping the empty places at the end). Then after each operation \( M \) is the vector of the ids of the heap; the events of an operation are at most \( \lceil \log_d ( ( d - 1 ) s + 1 ) \rceil + 1 \), and with NoObservers the code of the operation is that of the plain heap.
Indeed, a walk up from the place \( i \) with the item \( x \) moves the parent \( p \) to \( i \) and goes on from \( p \), which is the exchange of \( x \) and its parent if \( x \) is thought of as being at \( i \); the walk down is the same with the least child. The insertion puts \( x \) at the place \( s \) and walks up from it, a change of key walks from the place of the item, and an erasure (and pop(), the erasure of the root) empties the place \( i \) of the item, moves the last item from \( s - 1 \) to \( i \), which is the exchange with the empty place that the first \( \mathrm{Relocated} \) tells, and walks from \( i \). Hence the events are, in order, the exchanges whose composition is the change of the vector, and their number is that of the levels walked by Lemma 1, plus one. The walks with the events are a second instance of the template of the walk, called only on the path on which someone wants \( \mathrm{Relocated} \); the operation tests listened of its events at compile time before the test at run time, so that with NoObservers both vanish, which the check of zero cost confirms against the heap before the subject policy, by the instructions and by the code.