Interviews are considered puzzles.

This commit is contained in:
2015-02-14 12:45:32 +04:00
parent 12af9d1b7f
commit 0f638a71f4
10 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,47 @@
//aschoedl@think-cell.com
#include <iostream>
#include <vector>
template<typename T, typename IT>
int binary_search( IT ib, IT ie, const T& e )
{
if ( ib == ie || e < *ib || *(ie-1) < e )
return -1;
auto base = ib;
auto im = (ib+(ie-ib)/2);
while ( ib != im )
{
if ( e < *im )
ie = im;
else
ib = im;
im = (ib+(ie-ib)/2);
}
return !(*ib < e) ? (ib - base) : -1;
}
void main ( void )
{
std::vector<int> v = { 0,1,2,3,4,4,4,4,5,6,7,8,9,11};
for ( int i = 0; i < v.size(); i++ ) {
int j = binary_search( v.begin(), v.end(), v[i] );
std::cout << v[i] << "->" << j << std::endl;
}
std::cout << binary_search( v.begin(), v.end(), 10 ) << std::endl;
std::cout << binary_search( v.begin(), v.end(), 12 ) << std::endl;
std::cout << binary_search( v.begin(), v.end(), -4 ) << std::endl;
std::vector<int> v0;
std::cout << binary_search( v0.begin(), v0.end(), 10 ) << std::endl;
std::vector<int> v1 = { 1 };
std::cout << binary_search( v1.begin(), v1.end(), -10 ) << std::endl;
std::cout << binary_search( v1.begin(), v1.end(), 10 ) << std::endl;
std::cout << binary_search( v1.begin(), v1.end(), 1 ) << std::endl;
}