VasilM

binary_search

Nov 22nd, 2012
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.50 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int a[100], x;
  6.  
  7. int bin_search( int L, int R ){
  8.     int k = (L+R)/2;
  9. //  if(( x > a[k] && x > a[R] ) || ( x < a[k] && x < a[L])) return -1; //stupid
  10.     if( L > R ) return -1;
  11.     if( x == a[k] ) return k;
  12.     x > a[k] ? bin_search( k+1, R ) : bin_search( L, k-1 );
  13. }
  14.  
  15. int main(){
  16.  
  17.     for( int i=0; i<10; i++ ) a[i] = 2*i;
  18.     for( int i=0; i<10; i++ ) cout <<i << ": "<< a[i] << endl;
  19.     while( cin >> x ){
  20.  
  21.     cout << bin_search( 0, 9 ) << endl;
  22.  
  23.     }
  24.     return 0;
  25. }
Advertisement
Add Comment
Please, Sign In to add comment