-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.cpp
More file actions
62 lines (48 loc) · 999 Bytes
/
BinarySearch.cpp
File metadata and controls
62 lines (48 loc) · 999 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
52
53
54
55
56
57
58
59
60
61
62
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long int ulli;
vector<int> takeInput() {
vector<int> inputArray;
int size;
cin >> size;
while (size--)
{
int v;
cin >> v;
inputArray.push_back(v);
}
return inputArray;
}
int binarySearch(vector<int> a, int l, int h, int s)
{
if (l == h)
{
if (a[l] == s)
return l + 1;
else
return 0;
}
else
{
int mid = (l + h) / 2;
if (s == a[mid])
return mid + 1;
if (s > a[mid])
return binarySearch(a, mid + 1, h, s);
else
return binarySearch(a, l, mid - 1, s);
}
}
int main()
{
vector<int> array = takeInput();
cout << "Enter the value you want to find: ";
int keyValue;
cin >> keyValue;
int rslt = binarySearch(array, 0, array.size() - 1, keyValue);
if (rslt == 0)
cout << "[WARNING] data not being found in the list!" << endl;
else
cout << "[SUCCESS] data being found in the posi: " << rslt << endl;
return 0;
}