Java Reference
In-Depth Information
Note that we call compareTo only once. The value returned ( cmp ) tells us all we need to know. If we are
comparing words or names and we want the case of the letters to be ignored in the comparison, we can use
compareToIgnoreCase .
The function can be tested with P r ogram P1.6.
Program P1.6
import java.util.*;
public class BinarySearchString {
final static int MaxNames = 8;
public static void main(String[] args) {
String name[] = {"Charles, Kandice", "Graham, Ariel",
"Graham, Ashleigh", "Greaves, Sherrelle", "Perrott, Chloe",
"Reyes, Aaliyah", "Reyes, Ayanna", "Seecharan, Anella"};
int n = binarySearch("Charles, Kandice", name, 0, MaxNames - 1);
System.out.printf("%d\n", n);
//will print 0, location of Charles, Kandice
n = binarySearch("Reyes, Ayanna", name, 0, MaxNames - 1);
System.out.printf("%d\n", n);
//will print 6, location of Reyes, Ayanna
n = binarySearch("Perrott, Chloe", name, 0, MaxNames - 1);
System.out.printf("%d\n", n);
//will print 4, location of Perrott, Chloe
n = binarySearch("Graham, Ariel", name, 4, MaxNames - 1);
System.out.printf("%d\n", n);
//will print -1, since Graham, Ariel is not in locations 4 to 7
n = binarySearch("Cato, Brittney", name, 0, MaxNames - 1);
System.out.printf("%d\n", n);
//will print -1 since Cato, Brittney is not in the list
} //end main
// binarySearch goes here
} //end class BinarySearchString
This sets up the array name with the names in alphabetical order. It then calls binarySearch with various names
and prints the result of each search.
One may wonder what might happen with a call like this:
n = binarySearch("Perrott, Chloe", name, 5, 10);
Here, we are telling binarySearch to look for "Perrott, Chloe" in locations 5 to 10 of the given array. However,
locations 8 to 10 do not exist in the array. The result of the search will be unpredictable. The program may crash or
return an incorrect result. The onus is on the calling program to ensure that binarySearch (or any other function) is
called with valid arguments.
Search WWH ::




Custom Search