forked from sarthakd999/Hacktoberfest2021-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearch.cpp
47 lines (43 loc) · 833 Bytes
/
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
# include <bits/stdc++.h>
using namespace std;
int main()
{
int n ;
cout<<" Enter no integers "<< endl;
cin >> n ;
cout<<" Enter Your numbers "<< endl;
vector<int> a(n);
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
int to_find;
cout<<" Enter no to search "<< endl;
cin>> to_find;
int low = 0 , high = n-1 ;
int mid;
cout<<" your key is "<< endl;
while (high - low > 1)
{
int mid = (high + low)/2;
if (a[mid]<to_find)
{
low = mid +1;
}
else
{
high = mid;
}
}
if (a[low]==to_find)
{
cout<<low << endl;
}
else if(a[high]== to_find)
{
cout<< high << endl;
}
else{
cout<<"Not Found";
}
}