-
Notifications
You must be signed in to change notification settings - Fork 0
/
binarySearch.cpp
43 lines (39 loc) · 997 Bytes
/
binarySearch.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
// Example program
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int find(vector<int> const& input, int value) {
size_t lo = 0;
size_t hi = input.size() - 1;
while(lo <= hi) {
auto midpoint = (lo + hi) / 2;
if(input[midpoint] == value) {
return midpoint;
}
else if(input[midpoint] >= input[lo]) {
if(input[midpoint] < value) {
lo = midpoint + 1;
}
else if(input[midpoint] > value){
hi = midpoint - 1;
}
}
else if(input[midpoint] > value) {
hi = midpoint - 1;
}
else if(input[hi] >= value) {
lo = midpoint + 1;
}
else {
hi = midpoint - 1;
}
}
return -1;
}
int main()
{
vector<int> v = {15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14};
auto index = find(v, 5);
cout << index;
}