|
ADS
Algorithms and Data Structures
|
The tree of losers of a tournament among \( k \) players, the structure of the merge of \( k \) sorted sequences (Knuth 5.4.1; the notes, section 5.1.3, use a heap of \( k \) pairs for the same purpose). More...
#include "ADS/Contract.h"#include "ADS/sort/Sorted.h"#include <algorithm>#include <cstddef>#include <functional>#include <optional>#include <utility>#include <vector>#include "ADS/priority/impl/LoserTree.tpp"Go to the source code of this file.
Classes | |
| class | ADS::LoserTree< T, C > |
| the tree of losers of \( k \) players, the winner the smallest key by less More... | |
Namespaces | |
| namespace | ADS |
Functions | |
| template<class T, class C = std::less<>> | |
| std::vector< T > | ADS::kWayMerge (const std::vector< std::vector< T > > &R, C less=C()) |
| the items of the sorted vectors of \( R \), merged through a tree of losers | |
The tree of losers of a tournament among \( k \) players, the structure of the merge of \( k \) sorted sequences (Knuth 5.4.1; the notes, section 5.1.3, use a heap of \( k \) pairs for the same purpose).
The \( k \) players are the leaves of a complete binary tree with \( k - 1 \) internal nodes, laid out as a heap (the leaf of the player \( i \) is the node \( k + i \), the parent of the node \( v \) is \( \lfloor v / 2 \rfloor \)); each internal node keeps the loser of the match played there, and the node 0 keeps the overall winner, the player with the smallest key, the lower index on equal keys, so that a merge through the tree is stable. When the winner gets a new key (the next item of its sequence) or runs out (an exhausted player loses every match), replace() replays only the matches on the path from its leaf to the root, against the losers stored there: exactly \( \lceil \log_2 k \rceil \) or \( \lfloor \log_2 k \rfloor \) comparisons (a match on equal keys is decided by the indices, with the same single call of less), no more, while a binary heap [see DaryHeap.h] pays up to \( 2 \log_2 k \) for its pop and push, since each level of its sift down compares the two children and then the item moved down. The construction plays the \( k - 1 \) matches once, \( O( k ) \).
kWayMerge() merges \( k \) sorted vectors through the tree, \( n \lceil \log_2 k \rceil + k \) comparisons at most for \( n \) items in all; in the external memory the same merge, fed by one block per sequence, is the step of the multiway mergesort [see ExternalSorting.h].
The contracts [see Contract.h]: \( k \ge 1 \); top() and replace() on a tree whose players are not all exhausted; the invariant, that the winner has a key not larger than that of every player, is checked after each replace(); kWayMerge() needs sorted sequences and gives their items sorted, an audit. The functions are defined in LoserTree.tpp.