|
ADS
Algorithms and Data Structures
|
The max-heap on a vector built by insertions, the construction of Williams, beside the bottom-up one of Floyd. More...
Files | |
| file | ADS/tree/HeapByInsertion.h |
| The max-heap on a vector built by insertions, the construction of Williams, beside the bottom-up one of Floyd [see Heapsort.h]. | |
Functions | |
| template<class T, class C = std::less<>> | |
| void | ADS::maxHeapSiftUp (std::vector< T > &A, std::size_t i, C less=C()) |
| \( A[ i ] \) up in the heap \( A[ 0 .. i ] \), with the order less; \( O( \log i ) \) time | |
| template<class T, class C = std::less<>> | |
| void | ADS::heapBuildByInsertion (std::vector< T > &A, C less=C()) |
| \( A \) made a max-heap by inserting its items one at a time; \( O( n \log n ) \) time | |
The max-heap on a vector built by insertions, the construction of Williams, beside the bottom-up one of Floyd.
The definitions, the invariants and the costs of the area are in Theory of trees.
| void ADS::heapBuildByInsertion | ( | std::vector< T > & | A, |
| C | less = C() ) |
\( A \) made a max-heap by inserting its items one at a time; \( O( n \log n ) \) time
In pseudocode (Williams, beyond the book):
\[\class{pseudocode}{\begin{array}{r@{\quad}l} 1 & \textbf{procedure}\ \mathrm{heapBuildByInsertion}( A ) \cr 2 & \quad \textbf{for}\ i \gets 1\ \textbf{to}\ n - 1\ \textbf{do} \ \mathrm{maxHeapSiftUp}( A , i ) \end{array}} \]
| void ADS::maxHeapSiftUp | ( | std::vector< T > & | A, |
| std::size_t | i, | ||
| C | less = C() ) |
\( A[ i ] \) up in the heap \( A[ 0 .. i ] \), with the order less; \( O( \log i ) \) time
In pseudocode (section 10.1, the insertion into a heap):
\[\class{pseudocode}{\begin{array}{r@{\quad}l} 1 & \textbf{procedure}\ \mathrm{maxHeapSiftUp}( A , i ) \cr 2 & \quad \textbf{while}\ i > 0\ \textbf{do}\quad \triangleright \ \text{the heap order holds but between } i \text{ and its parent} \cr 3 & \qquad p \gets \lfloor ( i - 1 ) / 2 \rfloor;\ \textbf{if} \ \textbf{not}\ A[ p ] < A[ i ]\ \textbf{then return} \cr 4 & \qquad A[ i ] \leftrightarrow A[ p ];\ i \gets p \end{array}} \]