Created
August 19, 2017 09:55
-
-
Save ahmedahamid/70b26d543d828e7e7adf2d9b6a616a7b to your computer and use it in GitHub Desktop.
Useful insights into Binary Search problems
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
// | |
// Finds the position of the smallest element in a cyclically sorted array. | |
// Copied verbatim from: http://elementsofprogramminginterviews.com/solutions/java/BinarySearchCircularArray.java | |
// | |
public static int searchSmallest(List<Integer> A) { | |
int left = 0, right = A.size() - 1; | |
while (left < right) { | |
int mid = left + ((right - left) / 2); | |
if (A.get(mid) > A.get(right)) { | |
// Minimum must be in A.subList(mid + 1, right + 1). | |
left = mid + 1; | |
} else { // A.get(mid) < A.get(right). | |
// Minimum cannot be in A.subList(mid + 1, right + 1) so it must be in | |
// A.sublist(left, mid + 1). | |
right = mid; | |
} | |
} | |
// Loop ends when left == right. | |
return left; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment