-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathBinarySearch_Recursive.cpp
More file actions
52 lines (47 loc) · 951 Bytes
/
BinarySearch_Recursive.cpp
File metadata and controls
52 lines (47 loc) · 951 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
43
44
45
46
47
48
49
50
51
52
#include<iostream>
#include<cmath>
using namespace std;
int binarySearch(int arr[], int beg, int end, int value){
if(beg == end){
if(arr[beg] == value){
return beg;
}
else{
return -1;
}
}
else{
int mid = floor(beg + end)/2;
if(value < arr[mid]){
return binarySearch(arr,beg,mid-1,value);
}
else if(value > arr[mid]){
return binarySearch(arr,mid+1,end,value);
}
else if(value == arr[mid]){
return mid;
}
}
}
int main(){
int n, value;
cout<<"Enter the number of elements in the array"<<endl;
cin>>n;
cout<<"Enter the value to search"<<endl;
cin>>value;
cout<<"Enter the array in ascending order"<<endl;
int arr[n];
int item;
for(int i=0;i<n;i++){
cin>>item;
arr[i] = item;
}
int valueAt = binarySearch(arr,0,n-1,value);
if(valueAt >= 0){
cout<<"Value found at "<<valueAt<<" index";
}
else{
cout<<"Value not found";
}
return 0;
}