Here's an implementation of finding the minimum element in a rotated array using binary search (one that is sorted in ascending order, and all elements are distinct).
Please let me know of any improvements that can be made to it.
import java.util.List;
public class RotatedArray {
/**
* Finds and returns the index at which the smallest value in a rotated array is located.
*
* @param rotatedArray a rotated array that's sorted in ascending order (all elements are distinct)
* @return the index of the smallest value, or -1 if rotatedArray is empty
*/
public int findReset(List<Integer> rotatedArray) {
if (rotatedArray.isEmpty()) {
return -1;
}
// when array is already sorted
if (rotatedArray.size() == 1 || rotatedArray.get(0) < rotatedArray.get(rotatedArray.size() - 1)) {
return 0;
}
int midpoint = rotatedArray.size() / 2;
// when left side is monotonically increasing
if (rotatedArray.get(0) < rotatedArray.get(midpoint)) {
return findReset(rotatedArray.subList(midpoint + 1, rotatedArray.size())) + midpoint + 1;
}
// Prevents stack overflow error from occurring (e.g. test case [1,2,3,4,0])
if (rotatedArray.size() == 2) {
return midpoint;
}
// when right side is monotonically increasing
return findReset(rotatedArray.subList(0, midpoint + 1));
}
}