forked from Andyy-18/CPP-BASICS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
R_binarysearch.cpp
63 lines (51 loc) · 1.11 KB
/
R_binarysearch.cpp
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
53
54
55
56
57
58
59
60
61
62
63
#include<bits/stdc++.h>
using namespace std;
void arrprint(int arr[],int s,int e){
for(int i=s;i<=e;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}
bool binarysearch(int *arr,int s,int e,int key){
cout<<endl;
arrprint(arr,s,e);
//base case
//element not found
if(s>e){
return false;
}
int mid=s+(e-s)/2;
cout<<"Value of mid: "<<arr[mid]<<endl;
//element found
if(arr[mid]==key){
return true;
}
if(arr[mid]>key){
return binarysearch(arr,mid+1,e,key);
}
if(arr[mid]<key){
return binarysearch(arr,s,mid-1,key);
}
}
int main()
{
int size;
cout<<"Enter the size of your array: "<<endl;
cin>>size;
int arr[size];
cout<<"Enter your numbers : "<<endl;
for(int i = 0; i < size; i++){
cin>>arr[i];
}
int key;
cout<<"Enter the key: "<<endl;
cin>>key;
bool ans=binarysearch(arr,0,size-1,key);
if(ans){
cout<<"key is present."<<endl;
}
else{
cout<<"key is absent."<<endl;
}
return 0;
}