/* This is a program that implements binary search. Laura Toma */ public class BinSearch { public static void main (String args[]) { final int SIZE = 100; ReadStream r = new ReadStream(); //declare and allocate array int[] a = new int [SIZE]; //initialize array in increasing order int i=0; while (i < SIZE) { a[i] =i; i++; } System.out.println("test array size: " + SIZE); //read target int target; System.out.print("Enter target: "); target = r.readInt(); r.readLine(); //binary search for target in a[] //two indices that repr the portion of a[] we are currently looking at int left, right; int middle=0; //this represents the middle between left and right boolean found; //initial values left = 0; right = SIZE-1; found = false; while (right >= left && found == false) { middle = (left + right)/2; if (a[middle] == target) found = true; if (a[middle] < target) left = middle +1; if (a[middle] > target) right = middle -1; } if (found == true) System.out.println("Found at position " + middle); else System.out.println("Not found"); } // end of main } // end of class