/**
* BinarySearch.java
*
* A class to demonstrated iterative binary search on a sorted array.
*
* Created: Tue Feb 11 14:30:59 2003
*
* @author Stuart C. Shapiro
*/
public class BinarySearch {
/**
* Returns the index within the array a of the first occurrence of the int i,
* or -1 if i does not occur in a.
*
a is assumed to be sorted from lower to higher ints.
*
* @param a the sorted int[]
to be searched.
* @param i an int
value to search for.
* @return the index of the first occurrence of i in a,
* or -1 if i does not occur in a.
*/
public static int indexOf(int[] a, int i) {
int min = 0;
int max = a.length - 1;
int mid;
while (min <= max) {
// The search range is a[min .. max]
mid = (min + max) / 2;
if (i == a[mid]) return mid;
else if (i < a[mid]) max = mid-1;
else min = mid+1;}
return -1;
}
/**
* Tests the indexOf method.
*
*/
private static void test(int[] a, int i) {
System.out.print(i + " is at position " + indexOf(a, i) + " of "
+ "\t{" + a[0]);
for (int j = 1; j < a.length; j++) {System.out.print(", " + a[j]);}
System.out.println("}");
}
/**
* Demonstrates iterative binary search.
*
* @param args a String[]
value
*/
public static void main (String[] args) {
int[] testarray = {2,4,25,43,43,46,54,54,85,285,541,564};
test(testarray, 54);
test(testarray, 1);
test(testarray, 99);
test(testarray, 999);
} // end of main ()
}// BinarySearch