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

The search by interpolation of section 12.1 in a sorted vector of numbers. More...

Files

file  ADS/search/InterpolationSearch.h
 The search by interpolation of section 12.1 in a sorted vector of numbers: in the part \( A[ i .. j ] \) the key \( v \) is looked for in the place.

Functions

template<class T, class F>
long ADS::interpolationSearch (const std::vector< T > &A, const T &v, F &&trace)
 the place of \( v \) in the sorted \( A \), or -1; trace( i , j , m ) on each probe (the ricercaInterpolata() of the book)
template<class T>
long ADS::interpolationSearch (const std::vector< T > &A, const T &v)
 the search of interpolationSearch() above, with no trace

Detailed description

The search by interpolation of section 12.1 in a sorted vector of numbers.

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

Function documentation

◆ interpolationSearch() [1/2]

template<class T>
long ADS::interpolationSearch ( const std::vector< T > & A,
const T & v )

the search of interpolationSearch() above, with no trace

◆ interpolationSearch() [2/2]

template<class T, class F>
long ADS::interpolationSearch ( const std::vector< T > & A,
const T & v,
F && trace )

the place of \( v \) in the sorted \( A \), or -1; trace( i , j , m ) on each probe (the ricercaInterpolata() of the book)

In pseudocode (section 12.1), the offset kept in \( [ 0 , j - i ] \):

\[\class{pseudocode}{\begin{array}{r@{\quad}l} 1 & \textbf{function}\ \mathrm{interpolationSearch}( A , v ) \cr 2 & \quad i \gets 0;\ j \gets n - 1 \cr 3 & \quad \textbf{while}\ i \le j\ \textbf{and}\ A[ i ] \le v \le A[ j ] \ \textbf{do} \cr 4 & \qquad m \gets i \text{ if } A[ i ] = A[ j ] \text{, else } i + \lfloor ( j - i ) ( v - A[ i ] ) / ( A[ j ] - A[ i ] ) \rfloor \cr 5 & \qquad \mathrm{trace}( i , j , m )\quad \triangleright\ \text{the probe, linear in } v \cr 6 & \qquad \textbf{if}\ v < A[ m ]\ \textbf{then}\ j \gets m - 1 \cr 7 & \qquad \textbf{else if}\ A[ m ] < v\ \textbf{then}\ i \gets m + 1 \cr 8 & \qquad \textbf{else return}\ m \cr 9 & \quad \textbf{return}\ -1 \end{array}} \]

Precondition
\( A \) is sorted
Postcondition
the result is -1 if and only if \( v \) is not in \( A \)