public class BinarySearch extends Object
java.nio.LongBuffer
, or a file consisting of fixed-size
records.
There are two ways to search these structures. For structures that are sorted,
you can implement BinarySearch.Accessor
: the search will provide that
interface with indexes to compare. Or, you can create an int[]
that holds sorted indexes into the original data structure, and implement
BinarySearch.IndexedComparator
: the search will provide the comparator
with indexes retrieved from that array.
In either case, you must implement a compare()
method that
compares an actual object instance against the instance stored at a particular
index in your data structure.
As with Arrays.binarySearch()
, each of these methods returns
the index if successful, (-(insertionPoint) - 1)
if not. The
specific meaning of insertionPoint will vary depending on the
method called; see the method docs for details.
Modifier and Type | Class and Description |
---|---|
static interface |
BinarySearch.Accessor<T>
Implement this interface if you're searching an already-sorted array-like
structure.
|
static interface |
BinarySearch.IndexedComparator<T>
Implement this interface if you have an
int[] that contains
sorted indexes into the array-like structure. |
Constructor and Description |
---|
BinarySearch() |
Modifier and Type | Method and Description |
---|---|
static <T> int |
search(BinarySearch.Accessor<T> accessor,
T value)
Searches a sorted array-like structure using the provided
Accessor . |
static <T> int |
search(int[] index,
T value,
BinarySearch.IndexedComparator<T> cmp)
Searches sorted array of indexes into some other array-like object (which
does not need to be sorted).
|
public static <T> int search(BinarySearch.Accessor<T> accessor, T value)
Accessor
. If the object is found, the returned value will
be the object's location within that structure.
If the object is not found, the value of the returned insertion point
will depend on the accessor's defined range. If the accessor's range
covers the entire structure, or if the object would appear within the
defined range, then the returned insertion point will indicate the
position where the object should be inserted. If the accessor covers
a subset of the structure, and the missing object would appear outside
that structure, then the insertion point will be just before or just
after the defined range, not the absolute position in the array.
This is best illustrated with examples.
Given the array ['B', 'D', 'F', 'H', 'J', 'L', 'N', 'P', 'R']
:
public static <T> int search(int[] index, T value, BinarySearch.IndexedComparator<T> cmp)