-
Notifications
You must be signed in to change notification settings - Fork 21.1k
Expand file tree
/
Copy pathRotatedBinarySearch.java
More file actions
60 lines (53 loc) · 1.91 KB
/
RotatedBinarySearch.java
File metadata and controls
60 lines (53 loc) · 1.91 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.thealgorithms.searches;
import com.thealgorithms.devutils.searches.SearchAlgorithm;
/**
* Searches for a key in a sorted array that has been rotated at an unknown pivot.
*
* <p>
* Example:
* {@code [8, 9, 10, 1, 2, 3, 4, 5, 6, 7]}
*
* <p>
* This is a modified binary search. When the array contains no duplicates, the
* time complexity is {@code O(log n)}. With duplicates, the algorithm still
* works but may degrade to {@code O(n)} in the worst case.
*
* @see <a href="https://en.wikipedia.org/wiki/Search_in_rotated_sorted_array">Search in rotated sorted array</a>
* @see SearchAlgorithm
*/
public final class RotatedBinarySearch implements SearchAlgorithm {
@Override
public <T extends Comparable<T>> int find(T[] array, T key) {
int left = 0;
int right = array.length - 1;
while (left <= right) {
int middle = (left + right) >>> 1;
int cmp = key.compareTo(array[middle]);
if (cmp == 0) {
return middle;
}
// Handle duplicates: if we cannot determine which side is sorted.
if (array[left].compareTo(array[middle]) == 0 && array[middle].compareTo(array[right]) == 0) {
left++;
right--;
continue;
}
// Left half is sorted.
if (array[left].compareTo(array[middle]) <= 0) {
if (array[left].compareTo(key) <= 0 && key.compareTo(array[middle]) < 0) {
right = middle - 1;
} else {
left = middle + 1;
}
} else {
// Right half is sorted.
if (array[middle].compareTo(key) < 0 && key.compareTo(array[right]) <= 0) {
left = middle + 1;
} else {
right = middle - 1;
}
}
}
return -1;
}
}