二进制搜索程序无法识别边界?

Binary search program won't recognize bounds?

本文关键字:识别 边界 搜索 程序 二进制      更新时间:2023-10-16

我正在编写一个简单的二进制搜索程序,其中包含 10 个元素。 这是我的代码;

int main(int argc, char *argv[]) {
    int query, pos;
    int A[10] = {0,1,2,3,4,5,6,7,8,9}; //contents of the array
    cout<<"enter query      =   ";
    cin>>query; 
    int x=(10-1)/2; //the middle ground
    bool found = false;
    if(query<A[x]){ //if query is less than A[x] search before i
        for(int i=0;i<=x;i++){
            if(A[i]==query){
                found=true;
                pos=i;
            }
        }   
    }
    if(query>A[x]){
            for(int i=4;i<10;i++){
            if(A[i]==query){
                found=true;
                pos=i;
            }
        }
    }   
    if (found=false){
        cout<<"NOT FOUND"<<endl;
    }
    else{
        cout<<"FOUND AT A["<<pos<<"]"<<endl;
    }
    return 0;
}

奇怪的是,如果我尝试搜索一个不存在的元素,它会返回 FOUND AT A[48092] 或其他东西。我哪里做错了?

您看到的数字是变量 pos 的值,您看到它的原因是因为拼写错误:

if (found=false)

应该是

if (found == false)