所以我有一個名爲bList的ints矢量,它已經有了信息。我在運行二進制搜索之前對它進行了排序。C++二進制搜索算法不起作用
//I have already inserted random ints into the vector
//Sort it
bubbleSort();
//Empty Line for formatting
cout << "\n";
//Print out sorted array.
print();
cout << "It will now search for a value using binary search\n";
int val = binSearch(54354);
cout<<val;
我的氣泡排序算法確實有效。
我讓它返回一個int,它是搜索值在列表中的位置。
//Its one argument is the value you are searching for.
int binSearch(int isbn) {
int lower = 0;
int upper = 19;//Vector size is 20.
int middle = (lower + upper)/2;
while (lower < upper) {
middle = (lower + upper)/2;
int midVal = bList[middle];
if (midVal == isbn) {
return middle;
break;
} else if (isbn > midVal) {
lower = midVal + 1;
} else if (isbn < midVal) {
upper - midVal - 1;
}
}
}
但由於某種原因,當我運行它時,它只是繼續運行,並沒有返回任何東西。
我建議你通過代碼,行步一行一行,一個調試器。 –
請注意,'return'後面的'break'語句不是必需的。 –
如果您正在查找的值不在數組中,您將在不返回任何內容的情況下到達函數的結尾。你至少應該返回一些形式爲'value_not_found'的結尾。 – SirGuy