-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathbinary_search.cpp
66 lines (58 loc) · 1.33 KB
/
binary_search.cpp
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
63
64
65
66
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define endl '\n'
#define MOD 1000000007
#define fastio() \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL);
int binarySearch(vector<int> &nums, int target)
{
int start = 0, end = nums.size() - 1;
while (start <= end)
{
int mid = start + (end - start) / 2;
if (nums[mid] == target)
{
return mid;
}
else if (nums[mid] < target)
{
start = mid + 1;
}
else
{
end = mid - 1;
}
}
return -1;
}
int main()
{
int noOfElements;
cout << "Please enter number of elements : ";
cin >> noOfElements;
vector<int> elements;
cout << "Please enter the elements one by one" << endl;
for (int i = 0; i < noOfElements; i++)
{
int a;
cin >> a;
elements.push_back(a);
}
sort(elements.begin(), elements.end());
int noToFind;
cout << "Please enter the number to search : ";
cin >> noToFind;
int index = binarySearch(elements, noToFind);
if (index != -1)
{
cout << noToFind << " found in the array" << endl;
}
else
{
cout << noToFind << " is not present" << endl;
}
return 0;
}