forked from Sanskriti-26/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.cpp
More file actions
46 lines (46 loc) · 898 Bytes
/
BinarySearch.cpp
File metadata and controls
46 lines (46 loc) · 898 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
#include<iostream>
#include<vector>
using namespace std;
void binarySearch(vector<int> &v, int key)
{
int low = 0;
int high = v.size() - 1;
int mid;
while (low <= high)
{
mid = (low + high) / 2;
if (v[mid] == key)
{
cout << "Found " << key << " at index " << mid << endl;
return;
}
else if (v[mid] < key)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
cout << "Not found " << key << endl;
}
int main()
{
vector<int> v ;
int n;
cout << "Enter the number of elements: ";
cin >> n;
cout << "Enter the elements: ";
for (int i = 0; i < n; i++)
{
int x;
cin >> x;
v.push_back(x);
}
int key;
cout << "Enter the key to search: ";
cin >> key;
binarySearch(v, key);
return 0;
}