![]() |
VOOZH | about |
Given a sorted and rotated array arr[] of distinct elements, find the index of given key in the array. If the key is not present in the array, return -1.
Examples:
Input: arr[] = [5, 6, 7, 8, 9, 10, 1, 2, 3], key = 3
Output: 8
Explanation: 3 is present at index 8.Input: arr[] = [3, 5, 1, 2], key = 6
Output: -1
Explanation: 6 is not present.Input: arr[] = [33, 42, 72, 99], key = 42
Output: 1
Explanation: 42 is found at index 1.
Table of Content
A simple approach is to iterate through the array and check for each element, if it matches the target then return the index, otherwise return -1. To know more about the implementation, please refer Introduction to Linear Search Algorithm.
The main Idea is to first finds the index of the smallest element (pivot), which is also the number of rotations applied to the sorted array. Once the pivot is known, the array is split into two sorted subarrays.
If the key is equal to the pivot element, its index is returned. If the pivot is at index 0, the entire array is already sorted, so a standard binary search is applied to the whole array. Otherwise, the key is compared with the first element: if it's greater than or equal, binary search is performed on the left half; if not, on the right half.
8
This approach applies a modified version of binary search directly to the entire rotated array. At every iteration, the middle element is checked against the key. If itβs not the key, we determine whether the left half or right half is sorted by comparing values at arr[lo] and arr[mid]. If the left half is sorted and the key lies within its range, we adjust hi = mid - 1; otherwise, we shift lo = mid + 1. If the right half is sorted and the key lies within its range, we move lo = mid + 1; else, hi = mid - 1.
8