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
|
include <iostream>
#include <iterator>
#include <vector>
#include <list>
#include <string>
namespace frek
{
template < typename ITERATOR, typename T >
bool binary_search( ITERATOR begin, ITERATOR end, const T& value )
{
if( begin == end ) return false ;
const auto n = std::distance( begin, end ) ;
const auto mid = std::next( begin, n/2 ) ;
if( *mid == value ) return true ;
else if( *mid < value ) return frek::binary_search( std::next(mid,1), end, value ) ;
else return frek::binary_search( begin, mid, value ) ;
}
template < typename SEQ, typename T >
bool binary_search( const SEQ& seq, const T& value )
{ return frek::binary_search( std::begin(seq), std::end(seq), value ) ; }
}
int main()
{
std::cout << std::boolalpha ;
const std::vector<int> vec { 1, 2, 3, 4, 5 } ;
for( int i = 0 ; i < 7 ; ++i ) std::cout << i << ' ' << frek::binary_search( vec, i ) << '\n' ;
std::cout << '\n' ;
std::list<std::string> lst ;
for( int v : vec ) lst.push_back( std::to_string(v) ) ;
for( int i = 0 ; i < 7 ; ++i ) std::cout << i << ' ' << frek::binary_search( lst, std::to_string(i) ) << '\n' ;
}
| |