From 870ec085551f3c0adc897b5f8fff0cecc020c7f4 Mon Sep 17 00:00:00 2001 From: Vahagn Khachatryan Date: Sun, 8 Feb 2015 23:04:49 +0400 Subject: [PATCH] think-cell: binary search. --- interviews/think-cell/interview.cpp | 47 +++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 interviews/think-cell/interview.cpp diff --git a/interviews/think-cell/interview.cpp b/interviews/think-cell/interview.cpp new file mode 100644 index 0000000..6f32611 --- /dev/null +++ b/interviews/think-cell/interview.cpp @@ -0,0 +1,47 @@ + +//aschoedl@think-cell.com + +#include +#include + +template +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 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 v0; + std::cout << binary_search( v0.begin(), v0.end(), 10 ) << std::endl; + + std::vector 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; +} +