在未排序的数组中搜索一个数字

search a number in an unsorted array

本文关键字:一个 数字 搜索 排序 数组      更新时间:2023-10-16

我有一个代码,它搜索数组中的给定条目,并返回该条目在数组中的位置,前提是知道数组中包含该数字。然而,一件奇怪的事情发生了。当我尝试用一些具体的数组测试代码时,代码对某些条目有效,而对其他条目无效。代码是这样的:

#include <iostream>
#include <cmath>
using namespace std;
int Find_entry(int data[], int n, int x)
{
    int a = (n/2);
    int b = n;
    int tmp = 0;
    while (x != data[a])
    {
        if (x > data[a])
        {
            tmp = a;
            a = (b+a)/2;
            b = b;
        }
        if (x < data[a])
        {
            a = tmp;
            b = a;
        }
    }
    return a;
}

(在以前的版本中,我使用floor函数将a中包含的数字四舍五入到整数部分,但我知道这不是必要的。)

我已经测试了这个程序,例如在这个主中的以下阵列:

int main()
{
    int n = 6; int x = 12;
    int array1[] = {3,12,5,9,7,11};
    cout << "The entry " << x << " is found at position " 
         << 1+Find_entry(array1, n, x) << endl;
    return 0;
}

当我像本例中那样键入x=12时,程序给出正确答案1。对于x=3、x=11和x=9也是如此。但是,如果我键入x=7或x=5,程序拒绝给出输出,我会得到一条类似的消息

"进程已终止,状态为1073741510(0分钟9秒)"。

有人能解释一下这里出了什么问题吗?如何修复代码??谢谢大家的回答。

不能对未排序的数组使用二进制搜索。使用线性搜索。

int Find_entry(int data[], int n, int x)
{
    int a = 0;
    while (a < n && x != data[a]) a++;
    return a;
}

二进制搜索仅适用于排序输入。