Optimize Binary Search Algorithm
- by Ganesh M
In a binary search, we have two comparisons one for greater than and other for less
than, otherwise its the mid value. How would you optimize so that we need to check only once?
bool binSearch(int array[], int key, int left, int right)
{
mid = left + (right-left)/2;
if (key < array[mid])
return binSearch(array, key, left, mid-1);
else if (key > array[mid])
return binSearch(array, key, mid+1, right);
else if (key == array[mid])
return TRUE; // Found
return FALSE; // Not Found
}