簡體   English   中英

為什么此代碼不產生輸出? 使用xcode的C ++二進制搜索

[英]Why this code does not produce output? c++ binary search using xcode

//使用c ++進行二進制搜索。 main函數不提供任何輸出。 這是簡單的二進制搜索算法實現。

#include <iostream>
using namespace std;
int BinarySearch(int *a, int x, int n ){
    int left = 0;
    int right = n-1;
    while(left<=right){
        int middle = left + right /2;
        if (x>a[middle]) {
            left = middle +1;
        }
        else if (x<a[middle]){
            right = middle -1;
        }
        else return middle;
    }
    return 1;
}

int main(int argc, const char * argv[])
{
    cout<<"Hello World";
    int a[] ={1,2,3,4,5,6,7,8,9,10};
    int x = 3;
    int n = 10;
    int var = BinarySearch(a, x, n);
    cout<<"The search result:"<<endl;
    cout<< var;
    return 0;

}

您缺少周圍的偏癱

int middle = left + right / 2;

一定是

int middle = (left + right) / 2;

而且您可能還想返回

return a[middle];    //instead of middle;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM