import java.util.Scanner;
public class ComparableSearch
{ public static void main(String[] args)
{ Scanner scan = new Scanner(System.in);
String[] staff = new String[5];
staff[0] = "Dick";
staff[1] = "Harry";
staff[2] = "Juliet";
staff[3] = "Romeo";
staff[4] = "Tom";
for (int i = 0; i < staff.length; i++)
System.out.println(staff[i]);
System.out.println("Enter name to search for:");
String name = scan.nextLine();
int j = search(staff, name);
System.out.println("Found in position " + j);
}
/**
Finds a value in a range of a sorted array, using the
binary search algorithm. The array objects must
implement the Comparable interface.
@param a the sorted array
@param from the first index in the range to search
@param to the last index in the range to search
@param v the object to search
@return the index at which the object occurs, or -1
if it does not occur in the array
*/
public static int search(Comparable[] a, Comparable value){
int low=0;
int high=a.length-1;
while (low<=high){
int mid=(low+high)/2;
int diff = a[mid].compareTo(value);
if (diff==0)
return mid;
if (diff<0)
low=mid+1; // search right half
else
high=mid-1; // search left half
}
return -1;
}
}
//@keywords: binary search, Comparable