Java Reference
In-Depth Information
We just discussed how to use a
Comparator
object for sorting arrays either to alter the
natural ordering or for sorting an array of objects that do not implement the
Comparable
interface. Now let's explore how to use the
binarySearch
method of
Arrays
to search
arrays sorted either in the natural order or with a
Comparator
.
Searching Arrays
The
Arrays
class contains a collection of
binarySearch
methods for searching arrays of
primitive types and objects. There is a pair of
binarySearch
methods for each Java array
type (except arrays of
boolean
s). For example, the following
binarySearch
methods are for
searching arrays of
longs
:
public static int binarySearch(long[] a, long key)
searches the entire array for
the specified
long
. The array must be sorted first.
public static int binarySearch(long[] a, int fromIndex, int toIndex, long
key)
searches a subset of the array for the specified
long
. The array must be sorted
first.
Similarly, there are two
binarySearch
methods for
byte
,
short
,
int
,
float
,
double
, and
char
arrays. There is also a pair of
binarySearch
methods for
Object
arrays:
public static int binarySearch(Object[] a, Object key)
public static int binarySearch(Object[] a, int fromIndex, int toIndex,
Object key)
The elements in the
Object
array must implement
Comparable
and be mutually
comparable. The
Arrays
class also contains a generics version of
binarySearch
for arrays
sorted using a
Comparator
, as follows:
public static <T> int binarySearch(T[] a, T key, Comparator<? super T> c)
public static <T> int binarySearch(T[] a, int fromIndex, int toIndex, T
key, Comparator<? super T> c)
All of the
binarySearch
methods require the array to be sorted prior to searching.
If the array is not sorted, then the result of the search is undefi ned. The return value of
binarySearch
is the index in the array where the key was found or negative if the given key
does not appear in the array.
Let's look at an example. The following statements search an array of
long
elements.
Study the code and see if you can determine its output:
6. long [] values = {432432L, 2342323L, 1244L, 89349L, 7898239L};
7. Arrays.sort(values);
8. long key = 432432L;
9. int index = Arrays.binarySearch(values, key);
10. System.out.println(key + “ found at index “ + index);
11. long key2 = 55555L;
12. int index2 = Arrays.binarySearch(values, key2);
13. System.out.println(key2 + “ found at index “ + index2);
Search WWH ::
Custom Search