0

How can I prevent a segmentation fault with a recursive binary search that does not find the number it it is looking for in the array.

int recursive_binary_search(int A[], int beg, int end, int key)
{
    if(end < beg)
        return -1;
    int mid = beg + end / 2;
    if(A[mid] == key)
        return mid;
    else if(A[mid] > key)
        return recursive_binary_search(A, beg, mid - 1, key);
    else
        return recursive_binary_search(A, mid + 1, end, key);
}
6
  • Do you handle std::exception at caller function? Commented Sep 15, 2013 at 18:36
  • Let me just take that part out. Commented Sep 15, 2013 at 18:36
  • 2
    your mid is not really a mid - missing parenthesis around beg + end Commented Sep 15, 2013 at 18:37
  • Does 'end' denote the last entry in the list or is it - as with stl - the entry after the end? If the latter, shouldn't you be writing if(end <= beg)? Commented Sep 15, 2013 at 18:38
  • 1
    e.g. if you have one element in A, would beg = 0 and end = 1? Commented Sep 15, 2013 at 18:39

2 Answers 2

1

The following code might be sufficient,

int recursive_binary_search(int A[], int beg, int end, int key)
{
    if(end < beg)
        cout<<"\nKey not Found";
    int mid = beg + end / 2;
    if(A[mid] == key)
        return mid;
    else if(A[mid] > key)
        return recursive_binary_search(A, beg, mid - 1, key);
    else
        return recursive_binary_search(A, mid + 1, end, key);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Turns out I forgot the () around the definition for mid.

Correcting the definition to

int mid = (beg + end) / 2;

fixed the problem.

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.