我一直在线性搜索算法的输出中挣扎了一段时间。我有搜索列表并返回位置的函数,如果找不到它,则返回-1,或找到匹配数字的数字值。有关如何使其正确输出的建议?C++线性搜索算法
输出需要通过testList进行搜索,看是否该号码是在stdList,并给予其位置
数量1(34)中的位于位置15
数2(74)为不在文件中。
编号3(56)未在文件中。
号4(103)中的位于位置75
等
这里是代码的主要部分,我与具有问题。
ARRAY_STANDARD指的是数组stdList的大小。
stdList正在比较的阵列针对
位置,不过是正在由功能searchList()
testList指的阵列正被比较stdList返回
值是元素我们正在寻找
//Outputs
if (position == -1)
cout << "Number " << testCount+1 << "(" << testList << ")" << " was not in the file." << endl;
else
cout << "Number " << testCount+1 << "(" << testList << ")" << " was located in position " << value << endl;
}
int searchList(int stdList [], int numElems, int value)
{
int index=0;
int position = -1;
bool found = false;
while (index < numElems && !found)
{
if (stdList[index] == value)
{
found = true;
position = index;
}
index++;
}
return position;
}
如果你的循环内容不使用循环迭代器'x',你为什么期望这样做有意义?你也可以删除循环并获得相同的输出。这里有些事情是严重错误的。 – Domi
它正在读数组,x只是一个计数器。 – Simsyy
_什么是读数组?您的循环每次只会计算相同的'if(position == -1)'语句,并且不会更改除'x'之外的任何变量的值。没有任何代码指向摘要中提到的'stdList'或'searchList()',没有更新'testList'或使用'value'的东西。 –