// Source code example for "A Practical Introduction // to Data Structures and Algorithm Analysis" // by Clifford A. Shaffer, Prentice Hall, 1998. // Copyright 1998 by Clifford A. Shaffer import java.io.*; // Driver class for binary search routine class Bsearchmain { static final int UNSUCCESSFUL = -1; // Perform a binary search in array for the element with // key value K. left and right are the left and right bounds, // respectively, of the part of the array to be searched. static int binary(int K, int[] array, int left, int right) { // Return position of the element in array (if any) with value K int l = left-1; int r = right+1; // l and r are beyond the bounds of array while (l+1 != r) { // Stop when l and r meet int i = (l+r)/2; // Look at middle of remaining subarray if (K < array[i]) r = i; // In left half if (K == array[i]) return i; // Found it if (K > array[i]) l = i; // In right half } return UNSUCCESSFUL; // Search value not in array } // Main routine for binary search driver public static void main(String args[]) throws IOException { Assert.notFalse(args.length == 2, "Usage: Bsearchmain "); int size = Integer.parseInt(args[0]); int K = Integer.parseInt(args[1]); int[] A = new int[size]; // Not a particularly exciting test case for (int i=0; i