在未排序的数组中搜索一个数字
search a number in an unsorted array
我有一个代码,它搜索数组中的给定条目,并返回该条目在数组中的位置,前提是知道数组中包含该数字。然而,一件奇怪的事情发生了。当我尝试用一些具体的数组测试代码时,代码对某些条目有效,而对其他条目无效。代码是这样的:
#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;
}
二进制搜索仅适用于排序输入。
相关文章:
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何获取一个数字的前3位
- 以C++输出一个数字三角形
- 反转一个数字程序不起作用,为什么?
- 如何让用户在 c++ 中选择一个数字
- 输出一个数字,该数字可能是三种类型之一
- C++在不使用pow或循环的情况下计算一个数字的幂
- 我必须更改我的数字最后一个数字和第一个数字,但不要使用仅带有整数或循环的函数.例如从 12345 到 52341
- 找到所有与自己求和的数字X的快速方法,去掉一个数字得到N
- C++[递归]将一个数字写成2的升序之和
- 试图找到一个数字的平方根,但代码不起作用。C++
- 我没有得到一个数字作为输出,而是一个表情符号
- 我的代码应该接受一个数字,并返回字母等级或"Grade is not valid"但 else 语句不起作用
- 将一个数字拆分为多个数字,每个数字只有一个有效位
- 你怎么编码,如果x不等于一个数字,程序就会退出
- 如何将整数数组相乘得到一个数字?
- 为无符号字符* 分配一个数字
- 如何以更有效的方式检查一个数字是否是素数?
- C++显示两个区间之间的数字的程序检查一个数字是否可以表示为两个素数的总和
- 字符串和双精度的麻烦,等值后再得到一个数字