Recursive binary search using Array. HELP?!

OK so I'm trying to write a program that performs recursive binary search. this program suppose to ask the user to enter a number to look for, it will then call binarySearch and display the result. if it does find the number, it's suppose to give me the position in which it was found, if it doesn't find it, it shows that it wasn't found.
an example run would be:
1. number to Find: 1 in position 1 //(It is not position 0!)
2. number to Find: 19 in position 10
3. number to Find: 5 in position 3
4. number to Find: 17 in position 9
5. number to Find: 21 fails //problem here
6. number to Find: 0 fails

OK so this is what i got now, it works except when i enter a bigger number than 19, it tells me that the number that is bigger than 19 is found in position 11, but there's no position 11, it only needs to go to position 10. can anyone help me fix this small problem, i don't know where it is?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <cmath>
using namespace std;

// the function
int binarySearch(int L[],int x, int first, int last)
{
  if (last >= first)  //first > last)
    {
      //return -1;
      int middle = (first + last) / 2;

      if (x == L[middle])
        return middle;
      else if (x < L[middle])
        return binarySearch(L, x, first, middle - 1);
      else //if(x > L[middle])
        return binarySearch(L, x, middle + 1, last);
    }
  else
    return -1;//(first + 1);    // failed to find key
}


int main()
{
  /* int myList[size] = n;
  int myfirst = 0;
  int mylast = n - 1;
  int findthis;*/

  int myList[] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};

  //int size;
  //int myList[size];
  //int n = myList[10];
  int myfirst = 0;
  int mylast = 10;//n - 1;
  int findthis;
  //int i = 0;

  cout << "Please enter a number to find: " << endl;
  cin >> findthis;


  int resultloc = binarySearch(myList, findthis, myfirst, mylast);
  if ( resultloc == -1 )
    {
      cout << "number not found" <<endl;
    }
  else
    {
      cout <<" number is found in position " << resultloc + 1 << endl;//binarySearch(myList, findthis, myfirst, mylast) <<endl;
    }

  /*if(resultloc == middle)
    {
      cout << findthis << " was found in position " << middle << endl;
      }*/

  return 0;
}
I copied your code and it seems to work fine.

I tried it with 20; 45; 875; and 243432, and each time, I get

number not found
That's very strange, what compiler are you using?
i'm using g++ putty
That's the same one I'm using. Try copying the code you posted here into another file and try compiling it. Maybe you accidentally deleted a character or line or something in your original file.
Topic archived. No new replies allowed.