二分查找(Binary Search)函数异常:非中间元素搜索无输出请求修复
二分查找程序问题排查与修复
核心问题分析
你的代码存在3个关键错误,导致非中间元素搜索无输出:
- 循环逻辑错误:用固定次数的
for (int i = 0; i < n; i++)循环不符合二分查找逻辑,正确的应该是在low <= high的条件下持续搜索,固定次数循环可能提前终止或做无效遍历。 - 区间调整逻辑完全颠倒:数组是升序排列,当
arr[mid] > target时,目标应该在左半区间,你却错误地把low设为mid+1;当arr[mid] < target时,目标在右半区间,你却把high设为mid-1,直接丢失了正确的搜索范围。 - 未处理查找失败场景:当目标不在数组中时,函数返回-1,但
main函数没有接收这个返回值并给出提示,导致用户看不到任何反馈。
另外补充:int arr[limit];是C风格的变长数组,不属于C++标准写法,建议用std::vector替代,避免潜在内存问题。
修复后的完整代码
#include <iostream> #include <vector> using namespace std; void input_array(vector<int>& arr, int n); int binary_search(const vector<int>& arr, int target); int main() { int limit; cout << "Enter The Limit For An Array:- "; cin >> limit; vector<int> arr(limit); input_array(arr, limit); int target; cout << "Enter The Number to find its position:- "; cin >> target; int result = binary_search(arr, target); if (result != -1) { cout << "The Position of The Given Target is :- " << result << endl; } else { cout << "Target not found in the array." << endl; } return 0; } void input_array(vector<int>& arr, int n) { cout << "Enter The Number in Increasing Order " << endl; for (int i = 0; i < n; i++) { cout << i+1 << ". Enter Number :- "; cin >> arr[i]; } } int binary_search(const vector<int>& arr, int target) { int low = 0; int high = arr.size() - 1; while (low <= high) { int mid = low + (high - low) / 2; // 避免low+high溢出 if (arr[mid] == target) { return mid; } else if (arr[mid] > target) { high = mid - 1; // 目标在左半区间,缩小右边界 } else { low = mid + 1; // 目标在右半区间,缩小左边界 } } return -1; // 未找到目标 }
关键修复说明
- 替换循环为
while (low <= high):这是二分查找的标准循环条件,确保覆盖所有可能的搜索区间。 - 修正区间调整逻辑:让
high和low的更新完全符合升序数组的搜索规则。 - 改用
std::vector:符合C++标准,内存管理更安全。 - 处理返回值:在
main函数中接收查找结果,分别处理找到和未找到的场景,给出明确输出。 - 优化
mid计算:用low + (high - low)/2替代(low+high)/2,避免整数溢出问题。
内容的提问来源于stack exchange,提问作者temporary
相关产品推荐
相关产品推荐

