The binary search is useful for finding data in sorted sets. It works by testing if the middle element of the set is greater than or less then the element searched for, and recursively searchs either the top half or the bottom half of the set if the elements don't match.

This technique is pretty fast, and only requires lg(n) comparisons or thereabouts for a set of n elements. The downside is that the set must already be sorted, but it's still generally useful.

A recursive implementation in C:

/* does a binary search. you can tell it's failed if a[x] != x. heh. */
int bsearch(int *a, int len, int x)
{
    int p = len / 2;

    if(a[p] == x)
        return p;
    if(p != 0) {
        if(a[p] > x)
            return bsearch(a, len - p, x);
        if(a[p] < x)
            return bsearch(a+p, len - p, x) + p;
    } return 0;
};

BinarySearch (last edited 2008-07-09 05:48:10 by localhost)