views:

717

answers:

3

How would I implement a binary search using just an array?

+3  A: 

Assuming you're looking for a language-independant answer, Wikipedia has all the info...

http://en.wikipedia.org/wiki/Binary_search

Ty
+12  A: 

Ensure that your array is sorted since this is the crux of a binary search.

Any indexed/random-access data structure can be binary searched. So when you say using "just an array", I would say arrays are the most basic/common data structure that a binary search is employed on.

You can do it recursively (easiest) or iteratively. Time complexity of a binary search is O(log N) which is considerably faster than a linear search of checking each element at O(N). Here are some examples from Wikipedia: Binary Search Algorithm:

Recursive:

BinarySearch(A[0..N-1], value, low, high) {  
    if (high < low)  
        return -1 // not found  
    mid = low + ((high - low) / 2) 
    if (A[mid] > value)  
        return BinarySearch(A, value, low, mid-1)  
    else if (A[mid] < value)  
        return BinarySearch(A, value, mid+1, high)  
    else
       return mid // found
    }

Iterative:

  BinarySearch(A[0..N-1], value) {
   low = 0
   high = N - 1
   while (low <= high) {
       mid = low + ((high - low) / 2)
       if (A[mid] > value)
           high = mid - 1
       else if (A[mid] < value)
           low = mid + 1
       else
           return mid // found
   }
   return -1 // not found
}
Simucal
Remember to watch for overflow when calculating mid. (see http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html )
Firas Assaad
@Firas Assad, Thanks, updated code to show the fix associated with preventing the overflow
Simucal
+1  A: 

The single comparison version is fast and concise

int bsearch_double(const double a[], int n, double v) {
  int low = 0, mid;
  while (n - low > 1) {
    mid = low + (n - low) / 2;
    if (v < a[mid]) n   = mid;
    else            low = mid;
  }
  return (a[low] == v) ? low : -1;
}
Jed