Code RoomBinary search returns wrong index
MediumPrep Room Coding #1679

Binary search returns wrong index

Code reviewAlgorithms & data structuresMid–Senior~25 min

Review this Java binary search. It is supposed to return the index of `target` or -1.

What a strong answer looks like

Separate real bugs from style. Rank issues by severity, point at the root cause rather than the symptom, and suggest a concrete fix, specific and kind.

0:00 of about 25 min
Mark a line and say what kind of problem it is.0 findings
1static int search(int[] a, int target) {
2 int lo = 0, hi = a.length;
3 while (lo < hi) {
4 int mid = (lo + hi) / 2;
5 if (a[mid] == target) {
6 return mid;
7 } else if (a[mid] < target) {
8 lo = mid;
9 } else {
10 hi = mid;
11 }
12 }
13 return -1;
14}
Which questions mattered is sealed until you submit. Telling you now would just be handing over the edge cases.