Logo

Programming-Idioms

  • Ruby
  • Php

Idiom #124 Binary search for a value in sorted array

Write the function binarySearch which returns the index of an element having the value x in the sorted array a, or -1 if no such element exists.

function binarySearch(array $a, $x)
{
    $imin = 0;
    $imax = count($a) - 1;
    while ($imin <= $imax) {
        $imid = (int)floor($imin + ($imax-$imin) / 2);
        if ($a[$imid] === $x) {
            return $imid;
        }
        if ($a[$imid] < $x) {
            $imin = $imid + 1;
        } else {
            $imax = $imid - 1;
        }
    }
    return -1;
}
def binary_search(a, el)
  a.bsearch_index{|x| x == el} || -1
end

Returning -1 is required, however index -1 refers to the last element of an array. More idiomatic is returning nil (which bsearch_index does).
#include <vector>
template<typename T>
int binarySearch(const std::vector<T> &a, const T &x)
{
    if(a.size() == 0) return -1;

    size_t lower = 0;
    size_t upper = a.size() - 1;

    while(lower <= upper)
    {
        auto mid = lower + (upper-lower) / 2;

        if(x == a[mid])
        {
            return (int)mid;
        }
        else if(x > a[mid])
        {
            lower = mid + 1;
        }
        else
        {
            upper = mid - 1;
        }
    }

    return -1;
}

Check for an empty vector up front, otherwise size() will return an unsigned 0, and subtracting 1 will be a big number!

New implementation...
< >
programming-idioms.org