【发布时间】:2020-06-17 06:38:24
【问题描述】:
所以,我正在做一个算法,目的是运行二进制搜索。但问题是即使在函数内部运行的算法我的返回根本不起作用,我总是收到的返回是 0。 这是进行搜索的函数:
value_type* bsearch( value_type * first, value_type * last, value_type value ){
value_type* mid;
mid = (last - first)/2 + first;
if(first>last){
std::cout << "first>last" << value << *mid << '\n';
return nullptr;
}
if(*mid==value){
std::cout << "Found " << mid << " " << *mid << '\n';
return mid;
}
if(*mid>value){
last = mid - 1;
std::cout << "*mid>value " << mid << " " << *mid << '\n';
bsearch(first,last,value);
}else{
first = mid + 1;
std::cout << "*mid<value " << mid << " " << *mid << '\n';
bsearch(first,last,value);
}
return nullptr;
}
这是运行 bsearch 函数的函数。 result 总是等于 0,即使 mid 是一个有效的指针,所以输出总是“搜索失败!”。
void run_bsearch(){
value_type A4[]{ 1, 2, 3, 4, 5, 6, 7 };
std::cout << ">>> A4[ " << print( std::begin(A4), std::end(A4) ) << "]\n";
for ( auto i(0u) ; i <= (sizeof(A4)/sizeof(A4[0]))+1 ; ++i ){
std::cout << ">>> Looking for value \'" << i << "\' in A4: ";
value_type* result = bsearch( std::begin(A4), std::end(A4), i );
std::cout << "Result: "<<result << "\n";
if( result == nullptr ){
std::cout << "Search failed!\n";
}else{
std::cout << "Located target element at position " << result - std::begin(A4) << std::endl;
}
}
}
程序运行如下:
【问题讨论】:
-
需要返回递归调用的结果:
return bsearch(first,last,value); -
return bsearch(first, last, value);似乎更合适。 -
你说得对,非常感谢:)
标签: c++ pointers return binary-search