Binary search method


class BinSearch {

// This is an encapsulation of a binary search function that takes an array of
// ordered objects and a key and returns an object with 2 attributes namely
// index - the value of the array index
// found - a boolean indicating whether or not the key is in the array
// An object is returned because it is not possible in Java to pass basic types by
// reference to a function and so return two values
// the key is -1 if the element is not found

public static void search ( int key, int [] elemArray, Result r )
{
1.     int bottom = 0 ;
2.     int top = elemArray.length - 1 ;
        int mid ;
3.     r.found = false ;
4.     r.index = -1 ;
5.     while ( bottom <= top )
        {
6.          mid = (top + bottom) / 2 ;
7.          if (elemArray [mid] == key)
             {
8.               r.index = mid ;
9.               r.found = true ;
10.             return ;
             } // if part
            else
            {
11.            if (elemArray [mid] < key)
12.               bottom = mid + 1 ;
              else
13.                top = mid - 1 ;
            }
       } //while loop
14. } // search
} //BinSearch


(c) Ian Sommerville 2008