package rebelsky.exam2.solutions; 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 BinarySearcher { // +--------+-------------------------------------------------- // | 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 BinarySearcher(Comparator _metric) { this.metric = _metric; } // BinarySearcher(Comparator) // +----------------+------------------------------------------ // | Public Methods | // +----------------+ /** * Searches for findMe in stuff. This should take * O(log_2(stuff.length)) steps. * * @pre * (1) stuff must be in increasing order according to the previously-provided metric. metric.compare(stuff[i],stuff[i+1]) <= 0 for all "reasonable" i. * (2) findMe must be an object that metric can compare to elements of stuff. In particular metric.compare(findMe,stuff[i]) and metric.compare(stuff[i],findMe) must be valid calls. * (3) stuff must be non-empty. (It's stupid to look in an empty array.) * @post * (1) stuff is not changed. * (2) Returns the index of something equal to findMe. That is, returns an i such that metric.compare(stuff[i],findMe) == 0 * @exception Exception * If nothing equal to findMe appears in stuff. */ 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 BinarySearcher