The following is a slightly modified implementation of binary search that finds the first occurrence of an Integer key.
Is this still O(log n)? I'm having some trouble determining whether this becomes O(n) in the worst case.
private static Integer lowestRank(Integer[] a, Integer key) {
Integer lo = 0;
Integer hi = a.length - 1;
while (lo <= hi) {
Integer mid = lo + ((hi - lo) / 2);
if (key.compareTo(a[mid]) > 0) {
lo = mid + 1;
} else if (key.compareTo(a[mid]) < 0) {
hi = mid - 1;
// Modified here to return the first occurrence of the key, if it exists
} else if (lo < mid) {
hi = mid;
} else {
return mid;
}
}
return -1;
}