package rebelsky.exam2; import java.util.Comparator; /** * Something that knows how to do binary search on arrays using a * specified comparator. * * @author Samuel A. Rebelsky * @author YOUR NAME HERE */ public class BS { // +--------+-------------------------------------------------- // | Fields | // +--------+ /** * The comparator used to determine the order of * elements in an array. */ Comparator metric; // +--------------+-------------------------------------------- // | Constructors | // +--------------+ /** * Build a new searcher that uses a particular * comparator. */ public BS(Comparator _metric) { this.metric = _metric; } // BS(Comparator) // +----------------+------------------------------------------ // | Public Methods | // +----------------+ /** * WRITE ME! */ public int binarySearch(Object findMe, Object[] stuff) throws Exception { int lb = 0; // The lower-bound of the portion of interest int ub = stuff.length - 1; // The upper-bound while (lb <= ub) { int mid = (lb + ub)/2; int c = metric.compare(findMe, stuff[mid]); if (c == 0) // Found it! return mid; else if (c < 0) // Middle element too big! ub = mid-1; else // Middle element too small! lb = mid+1; } // while // Whoops, doesn't seem to be there throw new Exception("Not found!"); } // binarySearch(Object) } // class BS