Last active
June 27, 2018 20:31
-
-
Save scottashipp/db5a18c9ced1c6703fae70012f2c853f to your computer and use it in GitHub Desktop.
Find minimum in a sorted rotated array in O(log n) time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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