Skip to content

Instantly share code, notes, and snippets.

@scottashipp
Last active June 27, 2018 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottashipp/db5a18c9ced1c6703fae70012f2c853f to your computer and use it in GitHub Desktop.
Save scottashipp/db5a18c9ced1c6703fae70012f2c853f to your computer and use it in GitHub Desktop.
Find minimum in a sorted rotated array in O(log n) time
class FindMinComparing {
public int findMin(int[] arr) {
if(arr == null) {
throw new IllegalArgumentException("Received null array");
}
if(arr.length < 1) {
throw new IllegalArgumentException("Received zero-length array");
}
if(arr.length == 1) {
return arr[0];
}
return findMin(arr, 0, arr.length - 1);
}
int findMin(int[] arr, int lo, int hi) {
int mid = lo + ( (hi - lo) / 2);
if(mid > 0 && arr[mid] < arr[mid - 1]) {
return arr[mid];
} else if(arr[mid] > arr[hi]) {
return findMin(arr, mid + 1, hi);
} else {
return findMin(arr, lo, mid - 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment