-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbinarysearch.cpp
More file actions
45 lines (44 loc) · 947 Bytes
/
binarysearch.cpp
File metadata and controls
45 lines (44 loc) · 947 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
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
vector <int > arr;
cout<< " Enter the number of elemnents : ";
cin>>n;
int temp;
cout << "Enter the elements in sorted order :"<<endl;
for(int i = 0;i<n;i++)
{
cin>>temp;
arr.push_back(temp);
}
cout << " Enter the key you want to search : ";
int key;
cin>>key ;
int low = 0;
int high = n;
while(low != high)
{
//cout << low << ' '<<high<<endl;
int mid = (low + high)/2;
if(arr[mid] == key)
{
cout << "The key is found at position "<<mid + 1<<endl;
break;
}
else if(arr[mid] > key)
{
high = mid;
continue;
}
else if(arr[mid] < key)
{
low = mid + 1;
}
}
if(low == high )
{
cout << "The Key is not present in the array "<<endl;
}
}