Search an Element in a Sorted and Rotated Array in JavaScript
2 min readJun 1, 2022
Different approaches to solve this problem
Approach 1: Binary Search
- Use binary search to find the pivot in the array and divide it into two sub-arrays
- Note: If the pivot is -1 i.e. the array is sorted and not rotated then do a binary search on the entire array.
- Now do a binary search on those two sub-arrays.
Note 2: In a sorted rotated array (ascending order) the pivot is the only element for which the next element is smaller than it.
Time Complexity: O(log n)
Space Complexity: O(1)
Approach 2: Modified version of the approach 1
- Find the middle point in the array
mid = (left + right)/2
- If the middle element and target are equal then return mid
- If
arr[l…mid]
is sorted:
- If the key to be searched lies in the range from
arr[1] to arr[mid]
, recur forarr[l…mid]
- Else recur for
arr[mid+1 … h]
4. Else arr[mid+1 …. h]
must be sorted
- If the key to be searched lies in the range from
arr[mid+1] to arr[h]
, recur forarr[mid+1…h]
- Else recur for
arr[l…mid]
Time Complexity: O(log n)
Space Complexity: O(1)