-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchInSortedArray
More file actions
35 lines (33 loc) · 881 Bytes
/
Copy pathSearchInSortedArray
File metadata and controls
35 lines (33 loc) · 881 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
class Solution {
public:
int search(vector<int>& arr, int k) {
int low = 0, high =arr.size()-1;
while (low <= high) {
int mid = (low + high) / 2;
//if mid points the target
if (arr[mid] == k) return mid;
//if left part is sorted:
if (arr[low] <= arr[mid]) {
if (arr[low] <= k && k <= arr[mid]) {
//element exists:
high = mid - 1;
}
else {
//element does not exist:
low = mid + 1;
}
}
else { //if right part is sorted:
if (arr[mid] <= k && k <= arr[high]) {
//element exists:
low = mid + 1;
}
else {
//element does not exist:
high = mid - 1;
}
}
}
return -1;
}
};