-
Notifications
You must be signed in to change notification settings - Fork 110
Expand file tree
/
Copy pathshifted-binary-search.cpp
More file actions
39 lines (33 loc) · 894 Bytes
/
shifted-binary-search.cpp
File metadata and controls
39 lines (33 loc) · 894 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
#include <vector>
using namespace std;
int binarySearch(vector<int>& array, int target, int startIdx, int endIdx) {
if (startIdx > endIdx) return -1;
int mid = (startIdx + endIdx) / 2;
if (target == array[mid]) {
return mid;
} else if (target < array[mid]) {
return binarySearch(array, target, startIdx, mid - 1);
} else {
return binarySearch(array, target, mid + 1, endIdx);
}
}
int shiftedBinarySearch(vector<int> array, int target) {
// Write your code here.
int n = array.size();
int part = 0;
while (part < n) {
if (array[part - 1] > array[part]) {
part--;
break;
}
part++;
}
if (part == n) {
return binarySearch(array, target, 0, n - 1);
}
if (target >= array[0] && target <= array[part]) {
return binarySearch(array, target, 0, part);
} else {
return binarySearch(array, target, part, n - 1);
}
}