public abstract class BinarySearch extends Object
Utility class for implementing and working with binary searches. Binary searches over arbitrary structures can be performed by subclassing this class. Instances must capture the target (the key to be searched for), there is not a means of providing the key at search time.
Constructor and Description |
---|
BinarySearch() |
Modifier and Type | Method and Description |
---|---|
static <E extends Comparable<? super E>> |
forList(E needle,
List<? extends E> haystack)
Create a search over a list.
|
static int |
resultToIndex(int res)
Convert a possibly-negative binary search result to an index or insertion point.
|
int |
search(int start,
int end)
Perform a binary search across a range of integers.
|
protected abstract int |
test(int pos)
Test the value at position
pos , comparing it against the target. |
public int search(int start, int end)
Perform a binary search across a range of integers. This is much like Arrays.binarySearch(Object[], Object)
, but allows for searching over arbitrary indexed structures, and has defined behavior when the input sequence contains repeated elements (it always finds the first).
The efficiency guarantees of this method assume that there are not very many objects equal to the target element, as it does a linear scan to find the first once it finds one.
start
- The lower bound of the binary search (inclusive). Must be nonnegative.end
- The upper bound of the binary search (exclusive). Must be no less than start
.end
if the target is greater than all members). If multiple items match the target, this method is guaranteed to return the index of the first (unlike Arrays.binarySearch(Object[], Object)
).IllegalArgumentException
- if start
or end
is out of range.protected abstract int test(int pos)
Test the value at position pos
, comparing it against the target. p To understand this method, suppose that an array objs
of Comparable
objects is being searched. Then calling this method is equivalent to:
target.compareTo(objs[pos])
pos
, positive if it is greater, and 0 if the objects should be considered equal.public static <E extends Comparable<? super E>> BinarySearch forList(@Nonnull E needle, @Nonnull List<? extends E> haystack)
Create a search over a list.
needle
- The item to search for.haystack
- The list to searchE
- The element type.needle
in haystack
.public static int resultToIndex(int res)
Convert a possibly-negative binary search result to an index or insertion point.
res
- The resultres
is nonnegative) or insertion point (if it is negative).