[Geeks for Geeks] Search in a Rotated Array

Search in a Rotated Array

Given a sorted and rotated array A of N distinct elements which is rotated at some point, and given an element key. The task is to find the index of the given element key in the array A.

  • 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
class Solution{
public:
int search(int A[], int low, int high, int key){
int mi = -1, n = high;
int l = 0, r = n - 1;
while(l < r) {
int m = l + (r - l) / 2;
if(A[m] < A[r]) r = m;
else l = m + 1;
}
mi = r;

l = 0, r = n - 1;
while(l <= r) {
int m = l + (r - l) / 2;
if(A[(m + mi) % n] == key) return (m + mi) % n;

if(A[(m + mi) % n] > key) r = m - 1;
else l = m + 1;
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/20/PS/GeeksforGeeks/search-in-a-rotated-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.