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
|
#include <iostream>
/**
* Description: Recursive function to find position of key
* @param sorted array , key , lower bound , upper bound
* @return position at which the key exists or -1 if not found
*/
int binarySearch( int arr[] , int x , int low , int high )
{
if( low <= high ) {
int mid = ( high + low ) / 2;
if( arr[mid] == x ) {
return mid;
}
else if( arr[mid] > x ) {
binarySearch( arr , x , low , mid - 1 );
}
else {
binarySearch( arr , x , mid + 1 , high );
}
}
else {
return -1;
}
}
int main()
{
int arr[5] = { 1 , 2 , 3 , 4 , 5 };
std::cout << "Position of 3 is " << binarySearch( arr , 3 , 0 , 4 );
}
|