Java Reference
In-Depth Information
greater than the value, reversing its sign, and subtracting 1. For example, suppose you have an array of in-
tegers containing the element values 2, 4, 6, 8, and 10:
int[] numbers = {2, 4, 6, 8, 10};
You could search for the value 7 with the following statement:
int position = java.util.Arrays.binarySearch(numbers, 7);
The value of position is -4 because the element at index position 3 is the first element that is greater
than 7. The return value is calculated as -3-1 , which is -4 . This mechanism guarantees that if the value
sought is not in the array then the return value is always negative, so you can always tell whether a value is
in the array by examining the sign of the result. The magnitude of the value returned when the search fails is
the index position where you could insert the value you were looking for and still maintain the order of the
elements in the array.
Unless you are using a method that uses a comparator for searching arrays of objects, the class type of
the array elements must implement the Comparable<> interface. Here's how you could search for a string in
an array of strings:
String[] numbers = {"one", "two", "three", "four", "five", "six", "seven"};
java.util.Arrays.sort(numbers);
int position = java.util.Arrays.binarySearch(numbers, "three");
You must sort the numbers array; otherwise, the binary search doesn't work. After executing these state-
ments the value of position is 5.
TRY IT OUT: In Search of an Author
You could search the authors array from the previous example. Copy the source file for the Person class
from the previous example to a new directory for this example. Here's the code to try a binary search:
import java.util.Arrays;
public class TryBinarySearch {
public static void main(String[] args) {
Person[] authors = {
new Person("Danielle", "Steel"), new Person("John",
"Grisham"),
new Person("Tom", "Clancy"),
new Person("Christina",
"Schwartz"),
new Person("Patricia", "Cornwell"), new Person("Bill",
"Bryson")
};
Search WWH ::




Custom Search