2013-12-14 188 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