You need to enable JavaScript to run this app. C++自定义Bsearch二分查找代码运行异常 已存在元素被误判未找到
优惠活动
大模型
产品
解决方案
定价
更多

C++自定义Bsearch二分查找代码运行异常 已存在元素被误判未找到

二分查找异常问题排查

问题现象

内置有序数组{1,2,3,4,5,6,7,8,9},查找明确存在的元素3时,程序错误输出“未找到”。

原始代码

#include<stdlib.h>
#include<iostream>
using namespace std;
int Bsearch(int arr[],int item,int n)
{
 int low,mid,up;
 low=0;up=n-1;
 while(low<=up && item!=arr[mid])
 {
     mid=(low+up)/2;
     if(item==arr[mid])
        return mid;
     else if(item<arr[mid])
        low=mid+1;
     else
        up=mid-1;
 }
 return -1;
}
int main()
{
    int index,item;;
    int arr[]={1,2,3,4,5,6,7,8,9};
  cout<<"enter search item\n";
  cin>>item;
    index=Bsearch(arr,item,9);
    if(index!=-1)
    cout<<"element found at position"<<(index+1);
    else
    cout<<"element not found";
    return 0;
}

核心问题定位

  • 未初始化变量参与循环判断:while条件中直接引用arr[mid]做等值判断时,mid从未被赋值,是栈上的随机垃圾值,触发未定义行为,循环判断逻辑完全不可控。
  • 搜索边界更新逻辑颠倒:
    • 当待查找值item < arr[mid]时,目标值在左半区,应收缩上边界为mid-1,原代码错误将下边界设为mid+1,直接跳过左半区所有元素
    • 当待查找值item > arr[mid]时,目标值在右半区,应收缩下边界为mid+1,原代码错误将上边界设为mid-1,直接跳过右半区所有元素

修正后代码

#include<stdlib.h>
#include<iostream>
using namespace std;
int Bsearch(int arr[],int item,int n)
{
 int low=0, mid, up=n-1;
 while(low<=up)
 {
     mid=(low+up)/2; // 先计算中间位置,再做等值判断
     if(item==arr[mid])
        return mid;
     else if(item<arr[mid])
        up=mid-1; // 目标值在左半区,收缩上边界
     else
        low=mid+1; // 目标值在右半区,收缩下边界
 }
 return -1;
}
int main()
{
    int index,item;
    int arr[]={1,2,3,4,5,6,7,8,9};
    cout<<"enter search item\n";
    cin>>item;
    index=Bsearch(arr,item,9);
    if(index!=-1)
        cout<<"element found at position"<<(index+1);
    else
        cout<<"element not found";
    return 0;
}

内容的提问来源于stack exchange,提问作者Rohan Ray

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.22 10:06:07