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

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 ) \). More...

#include "ADS/Contract.h"
#include "ADS/sort/Sorted.h"
#include <algorithm>
#include <cstddef>
#include <functional>
#include <stdexcept>
#include <vector>
#include "ADS/sort/impl/CountingSort.tpp"

Go to the source code of this file.

Namespaces

namespace  ADS

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 ) \): \( 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 ) \).

The lower bound \( \Omega( n \log n ) \) of the sorts by comparisons does not apply, since it compares no item: it uses that the keys are small integers.

The contracts [see Contract.h]: each key must be in \( [ 0 , k ) \), a precondition checked key by key as the keys are counted (a key out of the range throws contract_violation when the preconditions are checked); the output sorted and made of the same keys is an audit. The functions are defined in CountingSort.tpp.

See also
A. Montresor, Algoritmi e Strutture Dati, 2025, section 2.7.5, https://algoritmicamente.it/materiali/libro/capitoli/cap02.pdf
Author
Donato Meoli
Dipartimento di Informatica
Università di Pisa