forked from AllAlgorithms/cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search_float.cpp
More file actions
48 lines (40 loc) · 853 Bytes
/
Copy pathbinary_search_float.cpp
File metadata and controls
48 lines (40 loc) · 853 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
#include<iostream>
#define eps 1e-3
using namespace std;
int binary_search_float(double a[],int lo,int hi,double key)
{
double res=-1;
while(hi>=lo)
{
int m = lo + (hi-lo) / 2;
if(a[m]-key >= eps){
hi = m-1;
}else if(abs(a[m]-key) <= eps){
res =m;
break;
}else{
lo = m+1;
}
}
return res;
}
int main(){
int n;
double key;
cout << "Enter size of array: ";
cin >> n;
cout << "Enter array elements: ";
double a[n];
for (int i = 0; i < n; ++i)
{
cin>>a[i];
}
cout << "Enter search key: ";
cin>>key;
double res = binary_search(a, 0, n-1, key);
if(res > -1)
cout<< key << " found at index " << res << endl;
else
cout << key << " not found" << endl;
return 0;
}