forked from ash638/code-for-hactoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.cpp
More file actions
42 lines (36 loc) · 744 Bytes
/
BinarySearch.cpp
File metadata and controls
42 lines (36 loc) · 744 Bytes
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
34
35
36
37
38
39
40
41
42
/*
Binary search using recursion.
*/
#include <iostream>
using namespace std;
//Function for binary search
int binary_search(int arr[], int n,int x,int start,int end){
if(start<=end){
int mid=(start+end)/2;
if(arr[mid]==x)
return mid;
else if(arr[mid]<x){
return binary_search(arr,n,x,mid+1,end);
}
else
return binary_search(arr,n,x,start,mid-1);
}
return -1;
}
int main()
{
int n,key;
cout<<"Enter number of elements in array:\n";
cin>>n;
cout<<"Enter elements of the array:\n";
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
cout<<"Enter the element which you want to search:\n";
cin>>key;
//calling the function
int ans=binary_search(arr,n,key,0,n-1);
cout<<"The index of desired element is: "<<ans<<endl;
return 0;
}