Optimize Binary Search Algorithm

Posted by Ganesh M on Stack Overflow See other posts from Stack Overflow or by Ganesh M
Published on 2009-03-23T15:24:11Z Indexed on 2010/05/29 11:12 UTC
Read the original article Hit count: 214

Filed under:
|
|
|

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
}

© Stack Overflow or respective owner

Related posts about c

    Related posts about algorithm