Reputation: 11
I have just written a binary search on c++, using arrays, but it isn't working for all of my tests.
#include <iostream>
using namespace std;
int bSearch(int arr[], int item);
int main() {
int testArr[] = {1, 3, 5, 7, 9, 10, 12, 13, 15, 16, 18, 20};
int result = bSearch(testArr, 18);
cout << "The result of binary search is " << result << endl;
return 0;
}
int bSearch(int arr[], int item) {
int start = 0;
int middle(0), guess(0);
int finish = sizeof(arr);
while(start <= finish) {
middle = (start + finish) / 2;
guess = arr[middle];
if(guess == item)
return middle;
else if(guess > item)
finish = middle - 1;
else
start = middle + 1;
}
return -1;
}
Can you explain me, why is it so?
Upvotes: 0
Views: 88
Reputation: 32727
In bSearch
, the parameter arr
is not an array, but a pointer to an int
. There is no information on if it points to an array of ints or the number of elements may be part of such an array.so sizeof(arr)
will be the size of a pointer (typically 4 or 8).
You'll need to pass number of elements the array holds to bSearch
, or use one of the standard containers that track the size (std::vector
or std::array
).
Upvotes: 2