2013-12-14 135 views
-2

我一直在线性搜索算法的输出中挣扎了一段时间。我有搜索列表并返回位置的函数,如果找不到它,则返回-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; 
} 
+4

如果你的循环内容不使用循环迭代器'x',你为什么期望这样做有意义?你也可以删除循环并获得相同的输出。这里有些事情是严重错误的。 – Domi

+0

它正在读数组,x只是一个计数器。 – Simsyy

+0

_什么是读数组?您的循环每次只会计算相同的'if(position == -1)'语句,并且不会更改除'x'之外的任何变量的值。没有任何代码指向摘要中提到的'stdList'或'searchList()',没有更新'testList'或使用'value'的东西。 –

回答

1

你似乎在上次编辑中丢失了几行代码。你想要做的(伪代码)这是什么:

for each element in testList:    <<<<< this is the for statement you lost 
    position = findElement(element, stdList) <<<<< this is the function you were not calling 
    if(position < 0): 
    print "not found" 
    else: 
    print "found element " element " at position " position 

把它拿走......

0

你应该改变你的方法在下列方式:

int searchList(int stdList [], int numElems, int value) 
{ 
    int index=0; 
    while (index < numElems) 
    { 
    if (stdList[index] == value) 
    { 
     return index; 
    } 
    index++; 
    } 
    return -1; 
} 
+0

这是更清洁,但不是他的问题。 – Floris

0
int searchList(int stdList [], int value) 
{ 
    for(int i = 0, length = sizeof(stdList); i < length; ++i) 
    { 
     if (stdList[i] == value) 
      return i; 
    } 
    return -1; 
} 
+2

只发布没有任何上下文或解释的代码并不是一个足够的答案。我建议你阅读[**如何回答**](http://stackoverflow.com/questions/how-to-answer)并展开它。 – brandonscript

0

成功输出。

int results; 
for(int i = 0; i < 22; i++) 
{ 
    results = searchList(stdList, ARRAY_STANDARD, testList[i]); 
    if (results == -1) 
     cout << "Number " << i+1 << "(" << testList[i] << ")" << " was not in the file." << endl; 
    else 
     cout << "Number " << i+1 << "(" << testList[i] << ")" << " was located in position " << results+1 << endl; 
} 
+1

很高兴你知道了。 – Floris