[AlgoExpert] Shifted Binary Search

Shifted Binary Search

  • Time : O(logn)
  • Space : O(1)
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
#include <vector>
using namespace std;

int shiftedBinarySearch(vector<int> array, int target) {
int n = array.size(), l = 0, r = n - 1;
while(l < r) {
int m = (l + r) / 2;
if(array[m] > array[r]) l = m + 1;
else r = m;
}

int small = r;
l = 0, r = n - 1;

while(l <= r) {
int m = (l + r) / 2;
int mid = (m + small) % n;
if(array[mid] == target) return mid;

if(array[mid] > target) r = m - 1;
else l = m + 1;
}
return -1;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/10/PS/AlgoExpert/shifted-binary-search/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.