HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

A recursive function that performs a binary search

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
searchfunctionperformsrecursivebinarythat

Problem

I created a recursive function that uses binary search to just return true if it finds the value and false if it does not.

I'm new to recursion and binary search so please let me know where I can improve upon.

/**
* Uses binary search O(log n). Returns true if the values is in the value array false if it's not. Recursive
*/
bool binarySearch( int value, int values[], int left, int right ) {

    //keep track of when the array will be empty and return false
    if ( right < left ) {
        return false;
    }

    //Find the middle of the array
    int mid = ( left + right ) / 2;

    //compare the value to the middle of the array. If it's a match return true, else move the left position and right position accordingly
    if( value == values[ mid ] ) {
        return true;
    } else if ( value < values[ mid ] ) {
        right = mid - 1;
    } else {
        left = mid + 1;
    }

    //return the function 
    return binarySearch( value, values, left, right );
}

Solution

You return a boolean to indicate whether the value was found or not. The function would be more useful if you returned an index at which the value was found (or -1 if not found). It's better information for the same amount of work.

It appears that left is the leftmost index to consider, and right is the rightmost index to consider. It would be more idiomatic to follow the convention of inclusive-exclusive bounds, with left being the leftmost index and right being just beyond the last element. That way, right - left indicates the number of elements in the array.

You've implemented the search using recursion, but it could also be done using just a loop. You would avoid the overhead of function calls and the possibility of stack overflow.

int mid = ( left + right ) / 2 is vulnerable to integer overflow if both indices are large. int mid = left + (right - left) / 2 would not overflow.

Context

StackExchange Code Review Q#156492, answer score: 3

Revisions (0)

No revisions yet.