Skip to content

Commit

Permalink
Create day29b_solved (#216)
Browse files Browse the repository at this point in the history
* Create day29b_solved

Binary Search Using Recursion

* Rename day29b_solved to day29b_shubhendra-20
  • Loading branch information
shubhendra-20 authored and MadhavBahl committed Feb 8, 2019
1 parent 111c595 commit 19a8d01
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions day29/CPP/day29b_shubhendra-20
@@ -0,0 +1,44 @@
/*
Author: Shubhendra Singh
Github: shubhendra-20
*/

#include <iostream>
using namespace std;

int binarySearch(int arr[], int l, int r, int x)
{
while (l <= r) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;

if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);

return binarySearch(arr, mid + 1, r, x);
}

return -1;
}
int main()
{
int n,i,x;
cin>>n;
int a[n];
for(i=0;i<n;i++)
{
cin>>a[i];
}
cin>>x;
int k= binarySearch(a,0,n-1,x);
if(k==-1)
{
cout<<"element not found";
}
else
{
cout<<"element found at index "<<k+1;
}
return 0;
}

0 comments on commit 19a8d01

Please sign in to comment.