I’m implementing the binary search algorithm in C++, but the algorithm isn’t returning the correct value. The code can be found here.
template<class T>
int binary_search(T search_value, T search_array[]) {
int mid; /* The middle element of the remaining array to be searched. */
int min = 0; /* The first index of the array. */
/* This forumla gives us the size of the array. */
int max = sizeof(search_array)/sizeof(search_array[0]);
/* Continue searching until min >= max. */
while (min < max) {
/* Compute the value of mid using a formula that won't produce a number
* larger than the maximum allowed value of an integer. */
mid = (max-min)/2 + min;
/* Depending the whether search_value is larger or smaller than the
* value of whatever is at search_array[mid], set one of mid and max
* equal to mid. */
if (search_value > search_array[mid])
min = mid + 1;
else if (search_value < search_array[mid])
max = mid + 1;
else {
return mid;
}
}
return -1;
}
Given an array {0, 1, 3, 5, 7, 9} and searching for 3, the function should return 2, the index of 3 in the array. My function is returning -1 though, which means 3 was not found in the array. Where’s the problem?
This approach is not good to compute the size of the array, it works only in the function where you create your array.
Pass the size of your array as a parameter of your function, it’s the easiest approach.