Binary Search Algorithms

The Binary search requires an ordered list.

Iterative Algorithm

int find (ArrayList list, Double target);
// Iterative binary search will return the index of the target element, else list length
{
   Boolean found = false;
   int mid;
   int first = 0;
   int last = list.size( ) - 1;
   while (first <= last && !found)
   {
      mid = (first + last) / 2;
      if (list.get(mid).equals(target))
         found = true;
      else
         if (list.get(mid) > target)
            last = mid - 1;
         else   first = mid + 1;
   }
   if (found)
      return mid;
   return -1;
}

Recursive Algorithm

int Find (ArrayList list, Double target, Double first, Double last)
// Recursive binary search will return the index of the target element, else list length
{
   int mid;
   if (first > last)
      return -1;
   mid = (first + last) / 2;
   if (list.get(mid).equals(target))
      return mid;
   if (list.get(mid) < target)
      return find(list, target, mid+1, last);
   return find(list, target, first, mid-1);
}


Continue to:  Unit 3 / Prev / Next