MysteriesOne 2019-01-10 15:15 采纳率: 100%
浏览 1024
已采纳

codeup 1934 问题 B: 找x,提交答案错误50%,二分查找是哪里没考虑到吗

题目描述
输入一个数n,然后输入n个数值各不相同,再输入一个值x,输出这个值在这个数组中的下标(从0开始,若不在数组中则输出-1)。

输入
测试数据有多组,输入n(1<=n<=200),接着输入n个数,然后输入x。

输出
对于每组输入,请输出结果。

样例输入
4
1 2 3 4
3
样例输出
2

本地调试看不出毛病,求大神帮看看

#include <iostream>
#include <algorithm>

using std::cin;
using std::cout;
using std::endl;
using std::sort;

const int MaxSize = 210;
int a[MaxSize];

int main(){

    int n,x,k;
    while(cin >> n){
        for( int i = 0 ; i < n ; i++ ){
            cin >> a[i];
        }
        sort( a , a + n );
        cin >> x;
        k = n / 2;
       for( int i = 0 ; i <= n ; k = ( i + n ) / 2 ){
           if( a[k] == x ){
               cout << k;
               break;
           }
           if( a[k] < x )
                i = k + 1;
            else if( a[k] > x )
                n = k - 1;
       }
       if(a[k] != x)
            cout << -1;
        cout << endl;
    }

    return 0;
}
  • 写回答

2条回答 默认 最新

  • qq_31920577 2019-01-10 15:39
    关注

    折半查找是不行的,折半查找有一个前提那就是:数组的数必须有序,不然效率低的可怜。下面我写的,比较简单,什么也没做处理,你要的功能基本实现,根据这个改下吧

    #include

    using namespace std;

    int main() {
    int n = 0;
    cin >> n;

    int* ptr = new(nothrow) int[n];
    for (auto i = 0; i < n; i++) {
        cin >> ptr[i];
    }
    
    int x = 0;
    cin >> x;
    
    auto j = 0;
    auto status = 0;
    for (; j < n; ++j) {
        if (ptr[j] == x) {
            status = 1;
            break;
        }
    }
    
    if (status == 0) {
        j = -1;
    }
    cout << j << endl;
    
    delete[] ptr;
    
    cin.get();
    cin.get();
    
    return 0;
    

    }

    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?