Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,13 @@
* <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.
* works but may degrade to {@code O(n)} in the worst case. The algorithm uses
* {@code O(1)} additional space and returns {@code -1} for null or empty input,
* or when the key is not present.
*
* @param array sorted array rotated at an unknown pivot
* @param key value to search for
* @return an index containing {@code key}, or {@code -1} if it is not present
*
* @see <a href="https://en.wikipedia.org/wiki/Search_in_rotated_sorted_array">Search in rotated sorted array</a>
* @see SearchAlgorithm
Expand All @@ -21,6 +27,10 @@ public final class RotatedBinarySearch implements SearchAlgorithm {

@Override
public <T extends Comparable<T>> int find(T[] array, T key) {
if (array == null || array.length == 0 || key == null) {
return -1;
}

int left = 0;
int right = array.length - 1;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,50 @@ void shouldHandleDuplicates() {
assertTrue(index >= 0 && index < array.length);
assertEquals(3, array[index]);
}

@Test
void shouldReturnMinusOneForNullArray() {
RotatedBinarySearch search = new RotatedBinarySearch();
assertEquals(-1, search.find(null, 1));
}

@Test
void shouldReturnMinusOneForEmptyArray() {
RotatedBinarySearch search = new RotatedBinarySearch();
assertEquals(-1, search.find(new Integer[0], 1));
}

@Test
void shouldFindElementInSingleElementArray() {
RotatedBinarySearch search = new RotatedBinarySearch();
assertEquals(0, search.find(new Integer[] {7}, 7));
}

@Test
void shouldReturnMinusOneWhenSingleElementArrayDoesNotContainKey() {
RotatedBinarySearch search = new RotatedBinarySearch();
assertEquals(-1, search.find(new Integer[] {7}, 8));
}

@Test
void shouldFindElementAtRotationPivot() {
RotatedBinarySearch search = new RotatedBinarySearch();
Integer[] array = {4, 5, 6, 7, 0, 1, 2};
assertEquals(4, search.find(array, 0));
}

@Test
void shouldFindElementsAtBothEnds() {
RotatedBinarySearch search = new RotatedBinarySearch();
Integer[] array = {4, 5, 6, 7, 0, 1, 2};
assertEquals(0, search.find(array, 4));
assertEquals(6, search.find(array, 2));
}

@Test
void shouldReturnMinusOneForMissingKeyInAllDuplicatesArray() {
RotatedBinarySearch search = new RotatedBinarySearch();
Integer[] array = {2, 2, 2, 2, 2, 2, 2, 2};
assertEquals(-1, search.find(array, 3));
}
}
Loading