请求协助调试/重构二分查找代码(仅允许修改三行)
Hey there! Let's tackle this binary search code—there are a couple of critical issues that can cause infinite loops or integer overflow, and we can fix everything with exactly three line changes. Here's the breakdown:
First, let's spot the problems in the original code:
- Integer Overflow: Calculating
m = (l + r) / 2can overflow whenlandrare large positive integers (since their sum might exceed the maximum value ofint). - Infinite Loop: When
A[m] <= X, settingl = mcan trap the loop in an infinite cycle. For example, ifl=0andr=1,m=0—ifA[0] <= X,lstays 0, and the loop conditionl < rnever becomes false. - Incorrect Final Check: After the loop,
lmight point to a position just past the target value, so checking onlyA[l]can miss the actual target.
Here's the fixed code with exactly three modified lines (marked with comments):
int binaryS(int[] A, int X) { int N = A.length; if (N == 0) { return -1; } int l = 0; int r = N - 1; while (l < r) { // Modified line 1: Avoid integer overflow with safer midpoint calculation int m = l + (r - l) / 2; if (A[m] > X) { r = m - 1; } else { // Modified line 2: Move left boundary forward to prevent infinite loops l = m + 1; } } // Modified line 3: Check the correct position after loop convergence if (l > 0 && A[l-1] == X) { return l-1; } return -1; }
Why these changes work:
- The midpoint calculation
l + (r - l)/2avoids overflow because it only subtracts first, ensuring we never exceed theintrange. - Setting
l = m + 1whenA[m] <= Xensures the left boundary always moves forward, breaking any potential infinite loops. The loop will eventually converge whenl == r. - After the loop,
lwill be either the first index whereA[l] > Xor equal toN(if all elements are <= X). CheckingA[l-1]covers the case where the target was the last valid element we checked before the loop ended.
This fixed version handles edge cases like empty arrays, target values at the start/end of the array, duplicate values, and large arrays without overflow issues.
内容的提问来源于stack exchange,提问作者mark00777
相关产品推荐
相关产品推荐

