1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <vector>
#include <random>
// create a random sequence of n elements filled with values in [minv,maxv]
// return a vector see: https://cal-linux.com/tutorials/vectors.html
std::vector<int> make_random_seq( std::size_t n, int minv, int maxv )
{
// default random number engine, seeded with the current time
// http://www.cplusplus.com/reference/random/default_random_engine/
static std::default_random_engine rng( std::time(nullptr) ) ;
std::vector<int> seq ;
// http://www.cplusplus.com/reference/random/uniform_int_distribution/
std::uniform_int_distribution<int> distrib( minv, maxv ) ;
while( seq.size() < n ) seq.push_back( distrib(rng) ) ;
return seq ;
}
// check if an element with value 'value' is present in the sorted sequence
// return the index of the element in the sequence if it was found
// return an invalid position if it was not found
std::size_t bin_search( const std::vector<int>& sorted_seq, int value )
{
// get an iterator to the first element in sorted_seq that is not less than v
// auto: http://www.stroustrup.com/C++11FAQ.html#auto
const auto iter = std::lower_bound( sorted_seq.begin(), sorted_seq.end(), value ) ;
// if such an element was found and it is equal to v, return the position of that element
if( iter != sorted_seq.end() && *iter == value ) return iter - sorted_seq.begin() ;
else return sorted_seq.size() ; // otherwise return an invalid position
}
int main()
{
const int SIZE = 40 ;
// generate a sequence of random integers
std::vector<int> seq = make_random_seq( SIZE, 1, 100 ) ;
std::sort( seq.begin(), seq.end() ) ; // sort the sequence
// print the sorted sequence using a range based loop
// http://www.stroustrup.com/C++11FAQ.html#for
for( int v : seq ) std::cout << v << ' ' ;
std::cout << '\n' ;
// binary search, and print out the result
// initialiser list: http://www.stroustrup.com/C++11FAQ.html#init-list
for( int v : { 13, 18, seq[SIZE/3], 40, seq[SIZE/2], 62, seq[ SIZE * 3/4 ], 80, 99 } )
{
const std::size_t pos = bin_search( seq, v ) ;
// if the position is valid, print out the posion
if( pos < seq.size() ) std::cout << v << " found at position " << pos << '\n' ;
else std::cout << v << " was not found\n" ;
}
}
|