Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ahmedahamid/70b26d543d828e7e7adf2d9b6a616a7b to your computer and use it in GitHub Desktop.
Save ahmedahamid/70b26d543d828e7e7adf2d9b6a616a7b to your computer and use it in GitHub Desktop.
Useful insights into Binary Search problems
//
// 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