Binary Search

Look at middle element of sorted array in range [first, last) until the target is found or run out of elements. Return index of target or last.

Analysis (same parameters as Sequential Search)

Objects Type Kind Movement Name
array of values int[ ] varying received arr
index of lower bound int varying received first
index of upper bound int varying received last
search target int varying received target
index of target int varying returned ---
index of midpoint int varying local mid
value at midpoint int varying local midValue
original last index int varying local origLast

Algorithm

  1. Initialize origLast to last
  2. While first < last do
    2.1
    Compute mid = (first+last)/2
    2.2
    Set midValue to arr[mid]
    2.3
    If target equals midValue then (found a match)
    2.3.1 Return mid
    2.4
    Else if target less than midValue then (in lower half)
    2.4.1 Set last to mid
    2.5
    Else (in upper half)
    2.5.1 Set first to mid+1
  3. Return origLast (target not found)

Code

// Precondition: first <= last
int BinSearch (const int arr[], int first, int last, int target)
{
   int mid,              // index of midpoint
       midValue,         // value at midpoint
       origLast = last;  // save original value of last

   // while the sublist is not empty
   while (first < last)
   {
      mid = (first+last)/2;
      midValue = arr[mid];
      if (target==midValue)        // found a match
         return mid;
      else if (target < midValue)  // search lower half
         last = mid;
      else                         // search upper half
         first = mid+1;
   }  // end while

   return origLast;                // target not found
}  // end BinSearch


Converted using latex2html on Tue Jan 31 21:56:54 CST 2006