【发布时间】:2015-04-13 20:57:55
【问题描述】:
这应该只是一个愚蠢的小问题(如果我能说得好的话)。在查看我教授的示例并观看 YouTube 视频时,我注意到当人们设置二进制搜索时,他们声明但不定义数组位置的变量(例如,第一、中、最后或低、中、高)。
教授的例子:
int bsearch(const int list[], int first, int last, int searchItem){
if(first <= last){
int mid = (first + last) / 2;
.......
如果不为 first/last/mid 设置值,这如何/为什么会起作用?
好的,这些回复是有道理的。但是,在我教授的例子中,我很难理解这种情况发生在哪里。我看到他在哪里返回 bsearch(),我认为仍然是未定义的参数,后来调用 binarySearch(),但只有 3 个参数。我看到我被否决了;我不确定这个人为什么或在哪里希望我转向编程问题。无论如何,这是完整的代码:
#include <iostream>
using namespace std;
int bsearch(const int list[], int first, int last, int searchItem)
{
if(first <= last) {
int mid = (first + last) / 2;
if(list[mid] == searchItem)
return mid;
else
if(list[mid] > searchItem)
return bsearch(list, first, mid-1, searchItem);
else
return bsearch(list, mid+1, last, searchItem);
}
else
return -1;
}
// Non-recursive shell for the recursive binary search function.
// This function does not use "first" and "last" as its parameters.
int binarySearch(const int list[], int listLength, int searchItem)
{
return bsearch(list, 0, listLength-1, searchItem);
}
int main() // testing recursive binarySearch function
{
int a[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int item;
cout << "Search item? ";
cin >> item;
cout << binarySearch(a, 10, item) << endl;
return 0;
}
【问题讨论】:
-
函数调用时提供的值。
-
mid已定义。函数参数是声明的,调用时会定义。 -
好吧,我想我意识到“last”和“searchItem”来自:“cout
标签: c++ binary-search