ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
HeapByInsertion.h

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

Detailed description

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.

Function documentation

◆ heapBuildByInsertion()

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

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}} \]

Postcondition
\( A \) is a max-heap

◆ maxHeapSiftUp()

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

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}} \]

Precondition
\( i < n \) and \( A[ 0 .. i - 1 ] \) is a max-heap (an audit)
Postcondition
\( A[ 0 .. i ] \) is a max-heap (an audit)