简体   繁体   English

使用递归的二进制搜索

[英]binary search using recursion

I can not figure out why this will not return the key, it seems to be skipping over the step, the logic i feel is straight, if midptr is less than key then search right else search left side. 我不知道为什么它不会返回键,似乎跳过了一步,我觉得逻辑是直截了当的,如果midptr小于键,则在右边搜索,在左边搜索。 but its not returning key it returns -1. 但它没有返回键,因此返回-1。 help? 救命? here is the code and function 这是代码和功能

#include<iostream>
using namespace std;


int binsrch(int *raw, unsigned int size, int key);




int main()
{
  int raw[] = {1,3,5,7,11,23, 48};
  cout << binsrch(raw, 7, 11) << endl;


  system("pause");
  return 0;
}



int binsrch(int *raw, unsigned int size, int key)
{
    int *begptr, *endptr ,*midptr;
//see if we already have the key

if(*raw == key)
  return key;

begptr = raw;
endptr = raw + (size - 1);
midptr = raw + (size / 2);

cout << "#" <<*midptr << " size:" << size<<  endl;
if(*midptr == key)
{
  return key;
}
else  if( *midptr < key) //Search Right
{
  cout << "#" <<*(midptr+1) << " size:" << size<<  endl;
  binsrch(midptr + 1, size / 2, key);
}
else if(*midptr > key) //Search Left
{
    cout << " #" <<*midptr << " size:" << size<<  endl;
    binsrch(begptr, size / 2, key);
}

return -1;
}

You forgot the return statements. 您忘记了return声明。 You should return the result of the recursive calls: 您应该返回递归调用的结果:

binsrch(midptr + 1, size / 2, key);

should be 应该

return binsrch(midptr + 1, size / 2, key);

Otherwise your initial call will execute the rest of the body and always end up returning -1 , unless you find the key before the first recursion. 否则,除非您在第一次递归之前找到键,否则您的初始调用将执行其余部分,并始终返回-1

By adding the return statement, you break the control flow of the recursive call (ie you don't return the "not found" value), and you will propagate the last return value all the way up in the call stack, until the first call, and finally return the value you want. 通过添加return语句,您将中断递归调用的控制流(即,您不返回“未找到”值),并且将最后一个返回值一直传播到调用堆栈中,直到第一个调用,最后返回您想要的值。

It all works fine, but you don't return the correct value. 一切正常,但是您没有返回正确的值。 In the else-if-statements you call the function recursive, but the returned values are not passed through to the initial call! 在else-if语句中,您将函数称为递归函数,但是返回的值不会传递给初始调用! Try: 尝试:

return binsrch(midptr + 1, size / 2, key);

and

return binsrch(begptr, size / 2, key);

That should work. 那应该工作。

-Edit: Well I guess I've been to slow ;) 编辑:嗯,我想我来的很慢;)

you should also add : 您还应该添加:

if(endptr == midptr) return -1;

after calculating endptr to avoid infinite loop incase of searching element not in array such as 21.. etc 在计算endptr之后避免无限循环,以防搜索元素不在数组(例如21)中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM