public class BinarySearchTest
1: // Fig 16.5: BinarySearchTest.java
2: // Use binary search to locate an item in an array.
3: import java.util.Scanner;
4:
5: public class BinarySearchTest
6: {
7: public static void main( String args[] )
8: {
9: // create Scanner object to input data
10: Scanner input = new Scanner( System.in );
11:
12: int searchInt; // search key
13: int position; // location of search key in array
14:
15: // create array and output it
16: BinaryArray searchArray = new BinaryArray( 15 );
17: System.out.println( searchArray );
18:
19: // get input from user
20: System.out.print(
21: "Please enter an integer value (-1 to quit): " );
22: searchInt = input.nextInt(); // read an int from user
23: System.out.println();
24:
25: // repeatedly input an integer; -1 terminates the program
26: while ( searchInt != -1 )
27: {
28: // use binary search to try to find integer
29: position = searchArray.binarySearch( searchInt );
30:
31: // return value of -1 indicates integer was not found
32: if ( position == -1 )
33: System.out.println( "The integer " + searchInt +
34: " was not found.\n" );
35: else
36: System.out.println( "The integer " + searchInt +
37: " was found in position " + position + ".\n" );
38:
39: // get input from user
40: System.out.print(
41: "Please enter an integer value (-1 to quit): " );
42: searchInt = input.nextInt(); // read an int from user
43: System.out.println();
44: } // end while
45: } // end main
46: } // end class BinarySearchTest
47:
48:
49: /**************************************************************************
50: * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and *
51: * Pearson Education, Inc. All Rights Reserved. *
52: * *
53: * DISCLAIMER: The authors and publisher of this book have used their *
54: * best efforts in preparing the book. These efforts include the *
55: * development, research, and testing of the theories and programs *
56: * to determine their effectiveness. The authors and publisher make *
57: * no warranty of any kind, expressed or implied, with regard to these *
58: * programs or to the documentation contained in these books. The authors *
59: * and publisher shall not be liable in any event for incidental or *
60: * consequential damages in connection with, or arising out of, the *
61: * furnishing, performance, or use of these programs. *
62: *************************************************************************/