/* BinarySearch.java */ import java.util.*; class BinarySearch { /** Searches for a element of a vector. * @param v is a Vector of Strings, sorted from lowest to highest * (by compareTo). * @param s is the String for which one is searching. * @returns true if and only if s equals one of the Strings in v. */ public static boolean bsearch(Vector v, String s) { int left, right; // If the String is anywhere, it is in positions left through right-1. // The String is not in a position before left. // The String is not in a position after right-1. if (v.size() == 0) return false; // Note: code in the book does // not handle empty Vectors left = 0; right = v.size(); while (left != right - 1) { int m = (right+left)/2; String sm = (String) v.elementAt(m); if (sm.compareTo(s)<0) { left = m; // Move left to the middle. } else if (sm.compareTo(s)>0) { right = m; // Move right to the middle. } else { left = m; right = m+1; } } return s.equals((String) v.elementAt(left)); } public static void main (String argv []) { Vector v = new Vector(); System.out.println("Binary search for A in: " + v + " is " + bsearch(v,"A")); v.addElement("A"); System.out.println("Binary search for A in: " + v + " is " + bsearch(v,"A")); System.out.println("Binary search for Z in: " + v + " is " + bsearch(v,"Z")); v.addElement("B"); v.addElement("C"); v.addElement("D"); v.addElement("E"); System.out.println("Binary search for A in: " + v + " is " + bsearch(v,"A")); System.out.println("Binary search for D in: " + v + " is " + bsearch(v,"D")); System.out.println("Binary search for E in: " + v + " is " + bsearch(v,"E")); System.out.println("Binary search for Z in: " + v + " is " + bsearch(v,"Z")); } }