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

The selection of section 17.1: the item of rank \( k \), the \( k \)-th smallest, \( 1 \le k \le n \), the median for \( k = \lceil n / 2 \rceil \), without sorting. More...

#include "ADS/Contract.h"
#include "ADS/sort/InsertionSort.h"
#include "ADS/sort/QuickSort.h"
#include <algorithm>
#include <cstddef>
#include <random>
#include <utility>
#include <vector>
#include "ADS/search/impl/Selection.tpp"

Go to the source code of this file.

Namespaces

namespace  ADS

Functions

template<class T, class R = std::mt19937>
T ADS::selection (std::vector< T > &A, std::size_t k, R *rng=nullptr)
 the item of rank \( k \), \( 1 \le k \le n \), of \( A \) (the selezione() of the book); with a generator the pivots are random, otherwise the first item of the part
template<class T>
T ADS::medianOfMedians (std::vector< T > &A, std::size_t k)
 the item of rank \( k \), \( 1 \le k \le n \), in linear time in the worst case

Detailed description

The selection of section 17.1: the item of rank \( k \), the \( k \)-th smallest, \( 1 \le k \le n \), the median for \( k = \lceil n / 2 \rceil \), without sorting.

  • selection(), of Hoare: the perno() of the book (partition()) puts its pivot in its place \( j \), the \( q = j - \mathit{start} + 1 \) smallest items before it, and the search goes on in the part that holds rank \( k \); with the pivot chosen at random, swapped to \( A[ \mathit{start} ] \) before the partition, the expected number of comparisons satisfies, the partition comparing the pivot with the other \( n - 1 \) items,

    \[ T( n ) \le n - 1 + \frac{2}{n} \sum_{q = \lfloor n / 2 \rfloor}^{n-1} T( q ) \le c n , \]

    linear for every input;
  • medianOfMedians(), of Blum, Floyd, Pratt, Rivest and Tarjan, which section 17.1 names without giving it, linear in the worst case: the pivot is the median of the medians of the groups of 5, which has at least \( 3 n / 10 \) items on each side, so that \( T( n ) \le T( n / 5 ) + T( 7 n / 10 ) + O( n ) = O( n ) \).

Both rearrange \( A \).

The contracts [see Contract.h]: \( 1 \le k \le n \), and the item returned has rank \( k \), i.e., fewer than \( k \) items are smaller and at least \( k \) are not larger, an audit in \( O( n ) \). The functions are defined in Selection.tpp.

See also
A. Montresor, Algoritmi e Strutture Dati, 2025, section 17.1, https://algoritmicamente.it/materiali/libro/capitoli/cap17.pdf
C. A. R. Hoare, Algorithm 65: Find, Communications of the ACM 4(7), 321-322, 1961, doi:10.1145/366622.366647
M. Blum, R. W. Floyd, V. Pratt, R. L. Rivest, R. E. Tarjan, Time bounds for selection, Journal of Computer and System Sciences 7(4), 448-461, 1973, doi:10.1016/S0022-0000(73)80033-9
Author
Donato Meoli
Dipartimento di Informatica
Università di Pisa