forked from tarunguptaraja/Algorithms-Library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_search.cpp
57 lines (47 loc) · 1.03 KB
/
binary_search.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
#include<bits/stdc++.h>
using namespace std;
#define max(a,b) a>b?a:b
#define min(a,b) a<b?a:b
#define O cout<<
#define I cin>>
#define f0(i,n) for(int i=0;i<n;i++)
#define f1(i,n) for(int i=1;i<n;i++)
#define speed_karo ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define ll long long
int binaryS(int ar[],int key,int l,int h){
while(l<=h){
int mid = floor((l+h)/2);
if(key==ar[mid]){
return mid;
}
else if(key<ar[mid]){
h = mid-1;
}
else{
l=mid+1;
}
}
return -1;
}
///recursive method
int binaryS2(int ar[],int key,int l,int h){
if(l<=h){
int mid = floor((l+h)/2);
if(key==ar[mid]){
return mid;
}
else if(key<ar[mid]){
return binaryS2(ar,key,l,mid-1);
}
else{
return binaryS2(ar,key,mid+1,h);
}
}
return -1;
}
int main(){
int ar[10]={1,2,3,4,5,6,7,8,9,10};
// int size= 7;
cout<<binaryS2(ar,7,0,9);
return 0;
}