package rebelsky.exam2; import java.math.BigInteger; import rebelsky.io.Pen; /** * A moderate test of binary search. Build an array containing the even * values between 0 and 32, inclusive. Search for all values between * -1 and 33. Even numbers have an index of half of their value. Odd * numbers should not be in the array. */ public class TestBinarySearch { public static void main(String[] args) { int SIZE = 17; // The size of the array Pen pen = new Pen(); int errors = 0; // How many errors we've observed. // Prepare the array to search BigInteger[] evens = new BigInteger[SIZE]; for (int i = 0; i < SIZE; i++) { evens[i] = BigInteger.valueOf(2*i); } // for // Create the searcher. BinarySearcher bs = new BinarySearcher(new BigIntegerComparator()); // Make sure all the evens work correctly. for (int i = 0; i < 2*SIZE; i += 2) { try { int pos = bs.binarySearch(BigInteger.valueOf(i), evens); if (i != pos*2) { pen.println(i + " incorrectly appeared at position " + pos); ++errors; } } catch (Exception e) { pen.println(i + " was incorrectly reported as being missing "); ++errors; } // catch(Exception) } // for // Make sure all the odds work correctly. for (int i = -1; i < 2*SIZE + 2; i += 2) { try { int pos = bs.binarySearch(BigInteger.valueOf(i), evens); pen.println(i + " incorrectly appeared at position " + pos); ++errors; } catch (Exception e) { // Yay! We wanted an exception. } } // for if (errors == 0) pen.println("All tests succeeded."); else pen.println("Found " + errors + " errors."); } // main(String[]) } // class TestBinarySearch