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

Counting Sort (section 2.7.5) of integers in \( [ 0 , k ) \). More...

Files

file  ADS/sort/CountingSort.h
 Counting Sort (section 2.7.5) of integers in \( [ 0 , k ) \): \( B[ v ] \) counts the occurrences of \( v \), then each \( v \) is written \( B[ v ] \) times in order; \( \Theta( n + k ) \) time and \( \Theta( k ) \) space, linear when \( k = O( n ) \).

Functions

template<RankStore Store, class T = std::ranges::range_value_t< std::remove_cvref_t< Store > >>
void ADS::countingSort (Store &&A, std::size_t k)
 \( A \), of integers in \( [ 0 , k ) \), in increasing order, by counting the occurrences of each key
template<class T>
void ADS::countingSort (std::vector< T > &A, std::size_t k)
 countingSort() above on a vector
template<SortRange R, class... P>
requires requires( std::vector< std::ranges::range_value_t< R > > & v , P &&... p ) { countingSort( v , std::forward< P >( p )... ); }
decltype(auto) ADS::countingSort (R &&A, P &&... p)
 countingSort() on the range \( A \) [see SortRange], the other arguments as for a vector, in place: on the span of its items if \( A \) is contiguous, on its view otherwise, since the sort reads the items by their ranks only

Detailed description

Counting Sort (section 2.7.5) of integers in \( [ 0 , k ) \).

The definitions, the invariants and the costs of the area are in Theory of sorting.

Function documentation

◆ countingSort() [1/3]

template<SortRange R, class... P>
requires requires( std::vector< std::ranges::range_value_t< R > > & v , P &&... p ) { countingSort( v , std::forward< P >( p )... ); }
decltype(auto) ADS::countingSort ( R && A,
P &&... p )

countingSort() on the range \( A \) [see SortRange], the other arguments as for a vector, in place: on the span of its items if \( A \) is contiguous, on its view otherwise, since the sort reads the items by their ranks only

◆ countingSort() [2/3]

template<class T>
void ADS::countingSort ( std::vector< T > & A,
std::size_t k )

countingSort() above on a vector

◆ countingSort() [3/3]

template<RankStore Store, class T = std::ranges::range_value_t< std::remove_cvref_t< Store > >>
void ADS::countingSort ( Store && A,
std::size_t k )

\( A \), of integers in \( [ 0 , k ) \), in increasing order, by counting the occurrences of each key

In pseudocode (section 2.7.5):

\[\class{pseudocode}{\begin{array}{r@{\quad}l} 1 & \textbf{procedure}\ \mathrm{countingSort}( A , n , k ) \cr 2 & \quad B \gets \text{a vector of } k \text{ zeros}\quad \triangleright \ \text{the occurrences} \cr 3 & \quad \textbf{foreach}\ a \in A\ \textbf{do}\ B[ a ] \gets B[ a ] + 1 \cr 4 & \quad j \gets 0 \cr 5 & \quad \textbf{for}\ i \gets 0\ \textbf{to}\ k - 1\ \textbf{do} \cr 6 & \qquad \text{write } i \text{ in } A[ j .. j + B[ i ] - 1 ];\ j \gets j + B[ i ] \end{array}} \]

Precondition
each key of \( A \) is in \( [ 0 , k ) \)
Postcondition
\( A \) is sorted, with the same keys (audit)