0

I am trying to implement recursive binary search in C++. However my algorithm cannot find the last two elements from the test array.I know that I am missing something. I have searched a lot for such a implementation of binary search algorithm but without success. Can anyone help me with it?

 bool isMember (int x, int a[], int size){
    if (size == 0) return false;
    return a[size/2] == x ||
          (a[size/2] < x && isMember (x,a+size/2,(size)/2)) ||
          (a[size/2] > x && isMember (x,a,(size)/2));
}
6
  • How do you tell if it's your middle element without one if statement? Commented Apr 23, 2016 at 16:46
  • What does the member function do? Commented Apr 23, 2016 at 16:50
  • @MeetTitan a[size/2] represents the middle element in every recursive call. My fault I meant isMember. Commented Apr 23, 2016 at 16:54
  • "Middle element" is ill-defined if you have an even number of elements. Commented Apr 23, 2016 at 16:55
  • 1
    You have a problem when size is odd – for instance, when it is 3, you will divide into a + 1 with size 1, and a with size 1. a[2] has gone missing. Commented Apr 23, 2016 at 16:58

1 Answer 1

3

No if statements here:

#include <iostream>

bool isMember (int x, int a[], int size)
{
    return size == 0 ? false
         : a[size/2] == x ? true
         : a[size/2] > x ? isMember(x, a, size/2)
         : isMember(x, a+size/2+1, size-(size/2+1));
}

int main()
{
    int v[]={1,2,4,8,16};

    for (int i=0; i<20; ++i)
        std::cout << i << ": " << isMember(i, v, 5) << std::endl;
    return 0;
}

Output:

0: 0
1: 1
2: 1
3: 0
4: 1
5: 0
6: 0
7: 0
8: 1
9: 0
10: 0
11: 0
12: 0
13: 0
14: 0
15: 0
16: 1
17: 0
18: 0
19: 0
Sign up to request clarification or add additional context in comments.

5 Comments

haha no if, only ternary operator :D nice, nice, I like it.
Changing the parameters in the method from the question it works without the ternary operator as well.
You can't change the question. If you want to change the requirements, ask a new question (yes, it's easy to do it without the ternary operator also).
No, no I just explain to @Vucko that it works without ternary operator too. Thank you Sam.
@samVarshavchik I know bro, it just sheer joy I feel when I see an answer like this :D

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.