1/11
Looks like no tags are added yet.
If every element in the array equals the search key, what do firstIndexOf and lastIndexOf return for an array of length n?
For a nonempty array, firstIndexOf returns 0 and lastIndexOf returns n - 1, so [3, 3, 3] gives 0 and 2. For an empty array, both return -1.
How does firstIndexOf behave differently from standard binary search when it finds a match?
Standard binary search can return mid as soon as it finds a match. My firstIndexOf saves mid and keeps searching left for an earlier match.
In the else branch, result = mid saves the match and hi = mid - 1 moves the search left. Because the return is after the loop, I keep searching as long as lo
Both return -1. A missing key never reaches the branch that saves a matching index.
In firstIndexOf, I initialize result to -1 before the loop. Only the equality branch updates it, so a missing key leaves -1 as the value I return. Before the loop → int result = -1; Equality branch → result = mid; After the loop → return result;
Returning 0 falsely says the first element matched, because 0 is a valid index. In my Autocomplete code, the first == -1 check would fail, so I'd run an extra search even though lastIndexOf still returns -1.
firstIndexOf checks indices 2, 0, and 1, then returns index 1. lastIndexOf checks indices 2, 3, and 4, then returns index 3, the last match it saved.
Both save result = mid when they find a match. The next line sends firstIndexOf left for an earlier match and lastIndexOf right for a later one. firstIndexOf → else { result = mid; hi = mid - 1; } lastIndexOf → else { result = mid; lo = mid + 1; }
No, because the first midpoint can land in the middle of several matches. Searching [1, 3, 3, 3, 5] for 3 would immediately return index 2, even though the first 3 is at index 1.
Since I call comparator.compare(key, a[mid]), a larger middle element gives a negative cmp. I set hi = mid - 1 and leave lo alone.
In firstIndexOf, I save the match with result = mid. I set hi = mid - 1 and leave lo alone so I can check for an earlier match.
Moving hi left is correct when a[mid] is larger than the key or when I've just saved a match. If a[mid] is smaller than the key, moving left would discard the side that could contain it, so I need lo = mid + 1.