0

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. but its not returning key it returns -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;
}
1
  • @Paulpro: The C++ version would be better; it's type-safe and potentially faster. Commented Apr 22, 2013 at 18:24

3 Answers 3

5

You forgot the return statements. 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.

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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! 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 ;)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.