-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathBinary Search
More file actions
51 lines (51 loc) · 921 Bytes
/
Binary Search
File metadata and controls
51 lines (51 loc) · 921 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
49
50
51
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,i,x,low,mid,high,val;
vector<int> V;
cout<<"Enter The Number Of Elements"<<endl;
cin>>n;
cout<<"Enter The Elements"<<endl;
for(i=0;i<n;i++)
{
cin>>x;
V.push_back(x);
}
cout<<"Sorted Array:"<<endl;
sort(V.begin(),V.end());
for(i=0;i<n;i++)
{
cout<<V[i]<<" ";
}
cout<<endl;
cout<<"Enter The Element To Be Searched"<<endl;
cin>>val;
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(V[mid]==val)
{
break;
}
else if(V[mid]>val)
{
high=mid-1;
}
else
{
low=mid+1;
}
}
if(low>high)
{
cout<<"Element Not Present"<<endl;
}
else
{
cout<<"Element Present At Index "<<mid<<endl;
}
return 0;
}