I have been thinking on how my binary search can be optimized. The code follows. What I have done so far:
All I could think of was in terms of handling different inputs.
Optimized worst case(one of the worst cases) when element being searched is out of bounds, i.e. searching a number lower than the lowest or higher than the highest. This saves O(logn) comparisions when it is a guarantee it won't be found in the input.
int input[15] = {1,2,2,3,4,5,5,5,5,6,7,8,8,9,10};
/*
* Returns index p if a[p] = value else -ve int.
* value is value being searched in input.
*/
int
binary_search (int * input, int low, int high, int value)
{
int mid = 0;
if (!input) return -1;
if (low > high) return -1;
/* optimize worst case: value not in input */
if ((value < input[low]) || (value > input[high]))
{ return -2; }
mid = (low + high)/2;
if (input[mid] == value) {
return mid;
}
if (input[mid] > value) {
return binary_search(input, low, mid -1, value);
} else {
return binary_search(input, mid+1, high, value);
}
}
Another worst case I can think of is when value being searched is next to the mid of the input or the first element. I think more generalized is the lower / higher bounds of input to each call of binary_search. This also requires the algorithm to take exact logn comparisons.
Any other suggestions on what other areas I can focus on improving. I don't need the code but a direction would be helpful. Thanks.