Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Will update the summary/description once things are more finalized.
Design (short version):
BinarySearch.intRange().find(0, 100, n -> n >= 35)
- find the first integer in range[0, 100)
which satisfies the predicaten >= 35
(in this case, yields 35 after about 7 steps)BinarySearch.longRange().find(1000L, 1000000L, n -> n >= 2048L)
- find the first long integer in range[1000L, 1000000L)
which satisfies the predicaten >= 2048L
We also have
BinarySearch.intRange().unsigned()
which treats the range as unsigned integers (0..0xFFFF_FFFF
), andBinarySearch.longRange().unsigned()
which is equivalent forlong
.There are also variations which allow you to provide your own midpoint function.
There are helpers to search ranges of things, for example, given:
We can search a
List<Item> list
for the givenname
using a helper like this:int idx = BinarySearch.intRange().findFirst(list, "Fred", 0, list.size(), (l, i) -> l.get(i).name())
Then
idx
will either contain the exact match, or the point into which the exact match would go.See https://bugs.openjdk.org/browse/JDK-8326330 for the original inspiration of this flexible implementation.
I'm not super happy with the API ergonomics (the factory methods). But it seemed better than having one
BinarySearch
class with 50 or more methods calledfind
. And the factory methods are all monomorphic and don't actually allocate anything, so the perf impact is expected to be minimal as these can be trivially inlined. But I'm open to other ideas in terms of API ergonomics and naming of classes.