Java Reference
In-Depth Information
Arrays.sort(authors);
// Sort using
compareTo() method
System.out.println("\nOrder after sorting into ascending
sequence:");
for(Person author : authors) {
System.out.println(author);
}
// Search for authors
Person[] people = {
new Person("Christina", "Schwartz"), new Person("Ned",
"Kelly"),
new Person("Tom", "Clancy"),
new Person("Charles",
"Dickens")
};
int index = 0;
System.out.println("\nIn search of authors:");
for(Person person : people) {
index = Arrays.binarySearch(authors, person);
if(index >= 0) {
System.out.println(person + " was found at index position " +
index);
} else {
System.out.println(person + " was not found. Return value is
" + index);
}
}
}
}
Directory "TryBinarySearch"
This example produces the following output:
Order after sorting into ascending sequence:
Bill Bryson
Tom Clancy
Patricia Cornwell
John Grisham
Christina Schwartz
Danielle Steel
In search of authors:
Christina Schwartz was found at index position 4
Ned Kelly was not found. Return value is -5
Tom Clancy was found at index position 1
Charles Dickens was not found. Return value is -4
How It Works
Search WWH ::




Custom Search