-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.cpp
More file actions
43 lines (43 loc) · 784 Bytes
/
binary_search.cpp
File metadata and controls
43 lines (43 loc) · 784 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
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout<<"Enter how many numbers :";
cin>>n;
vector<int>arr(n);
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
sort(arr.begin(),arr.end());
for(int x:arr){cout<<x<<" ";}
cout<<endl;
int a;
cout<<"Enter which value to check:";
cin>>a;
int low=0,high=n-1;
bool found=false;
while(low<=high)
{
int mid=(low+high)/2;
if(arr[mid]==a)
{
cout<<"The positon is of "<<a<<"is :"<<mid;
found=true;
break;
}
else if(arr[mid]<=a)
{
low=mid+1;
}
else
{
high=mid-1;
}
}
if(!found)
{
cout<<"Not Found";
}
}