⬅ Previous Topic
Count Occurrences in Sorted ArrayNext Topic ⮕
Search in Rotated Sorted Array with Duplicates⬅ Previous Topic
Count Occurrences in Sorted ArrayNext Topic ⮕
Search in Rotated Sorted Array with DuplicatesTopic Contents
Given a rotated sorted array and a target value key
, your task is to find the index of the target using an optimal binary search approach.
A rotated sorted array is a sorted array that has been rotated at some unknown pivot. For example, [4, 5, 6, 7, 0, 1, 2]
is a rotation of [0, 1, 2, 4, 5, 6, 7]
.
If the element is found, return its index. Otherwise, return -1
.
start = 0
, end = n - 1
.start ≤ end
, calculate mid = start + (end - start) / 2
.arr[mid] == key
, return mid
.arr[start] ≤ arr[mid]
is sorted:key
lies between arr[start]
and arr[mid]
.end = mid - 1
.start = mid + 1
.key
lies between arr[mid]
and arr[end]
.start = mid + 1
.end = mid - 1
.-1
.public class RotatedArraySearch {
public static int search(int[] arr, int key) {
int start = 0;
int end = arr.length - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (arr[mid] == key) return mid;
// Left half is sorted
if (arr[start] <= arr[mid]) {
if (key >= arr[start] && key < arr[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
// Right half is sorted
else {
if (key > arr[mid] && key <= arr[end]) {
start = mid + 1;
} else {
end = mid - 1;
}
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = {4, 5, 6, 7, 0, 1, 2};
int key = 0;
int index = search(arr, key);
System.out.println("Index of key: " + index);
}
}
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(1) | The key is found at the first mid-point without needing further comparisons. |
Average Case | O(log n) | Each step eliminates half the search space using binary search logic. |
Worst Case | O(log n) | In the worst case, the search continues until one element remains. |
O(1)
Explanation: The algorithm uses a constant number of variables, no extra memory.
⬅ Previous Topic
Count Occurrences in Sorted ArrayNext Topic ⮕
Search in Rotated Sorted Array with DuplicatesYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.