-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathbinary_search.cpp
More file actions
71 lines (56 loc) · 1.86 KB
/
binary_search.cpp
File metadata and controls
71 lines (56 loc) · 1.86 KB
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
67
68
69
70
71
/*
Binary Search
-----------
A searching algorithm that finds the position of a target value
within a sorted array.
Time complexity
---------------
O(log(N)), where N is the number of elements in the array.
Space complexity
----------------
O(1).
*/
#include <iostream>
#include <vector>
using namespace std;
int binarySearch(const int value, const vector<int>& sortedVect, const int low, const int high) {
// int mid = (low + high) / 2;
/* Incase the value of low and high is large then
formula (low+high)/2 fails in some case ,
therefore it's better to use this formula:-
int mid = low + (high-low)/2;
*/
int mid = low + (high-low)/2;
if (value == sortedVect[mid])
return mid;
else if (low <= high) {
if (value < sortedVect[mid]) {
// value must be between indices low and mid-1, if exists
return binarySearch(value, sortedVect, low, mid-1);
}
else if (value > sortedVect[mid]) {
// value must be between indices mid-1 and high, if exists
return binarySearch(value, sortedVect, mid+1, high);
}
}
return -1;
}
int main() {
int value;
cout << "Enter the value to search for : ";
cin >> value;
int size;
cout << "Enter the input size : ";
cin >> size;
vector<int> inputVect(size); // supposedly sorted values
cout << "Enter " << size << " integers in ascending order :\n";
for (int& val: inputVect)
cin >> val;
int index = binarySearch(value, inputVect, 0, size-1);
cout << "\n";
if (index != -1)
cout << "Found " << value << " at position " << (index + 1) << "\n";
else
cout << "Either " << value << " is not present among the input values, or the values aren\'t sorted\n";
return 0;
}