Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* Create day29b_solved Binary Search Using Recursion * Rename day29b_solved to day29b_shubhendra-20
- Loading branch information
1 parent
111c595
commit 19a8d01
Showing
1 changed file
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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; | ||
} |