为何二分查找示例代码中未添加数组首尾元素与目标值的检查判断语句?
Great question! Let's unpack why those extra checks aren't necessary, using your provided code as a reference.
First, let's note a small typo in your main method: when calling binary_search, you passed arr[0] as the left parameter—but left should be the starting index (0), not the value at that index. Fixing this will make the code run as expected.
Now, onto the core question:
The existing logic already covers boundary elements automatically
Think about how the recursion works. Eventually, when the search range narrows down to a single element (whenleft == right), themidcalculation will equalleft(andright). At that point, the code checksif (target == arr[mid])—which is exactly checking the boundary element. For example, if you're searching for-1in your sorted array:- The first few recursive calls narrow the range down to
left=0, right=0 midbecomes 0, and the code checksarr[0] == -1and returns the index correctly.
Same goes for searching20: the recursion will eventually reachleft=9, right=9, checkarr[9] == 20, and return the index.
- The first few recursive calls narrow the range down to
Adding extra checks would be redundant
Thoseleft/rightchecks don't add any new functionality—they just repeat a check that the existing logic will perform anyway. For example, if you added a check forarr[left] == targetat the start, you'd be checking that element before even calculatingmid—but if that element was the target, the recursion would eventually hit it when the range shrinks to that index anyway.Extra checks hurt code simplicity and maintainability
Binary search is all about keeping the logic tight and focused. Adding unnecessary conditionals makes the code longer, harder to read, and increases the chance of bugs (like accidentally checking values instead of indices, or introducing inconsistent logic between the extra checks and the mainmidcheck).
In short, the standard binary search pattern relies on narrowing the search range until every possible element (including the boundaries) is evaluated as a mid value—so there's no need for explicit checks on left or right.
内容的提问来源于stack exchange,提问作者Toast

