I have a direct buffer holding Integers that are already sorted (i.e. 1,1,3,3,3,3,7,7,….). Most values will occur multiple times. I want to find the first position of values I search for.
- Is there a search functionality directly working of buffers
built-into Java? (couldn’t find anything) - If not, is there any decent library providing such functionality?
-
If not, what search algorithm would recommend for implementation, given that:
- I will typically have millions of entries in my buffer
- Speed is very important
- It must return the first occurrence of the searched number
- I’d rather not have it modify the data as I will need the original data afterwards
EDIT: Thanks to all the posters suggesting Arrays.binarySearch(), but, as far as I know, direct buffers do not generally have a backing array. That’s why I was looking for an implementation that directly works on the buffer.
Also, each value can occur up to a thousand times, therefore a linear search after finding a landing point might not be very efficient. The comparator suggestion of dasblinkenlight might work though.
The best approach would be to code your own implementation of Binary Search for the buffers. This approach carefully avoids potential performance hits associated with creating views, copying large arrays etc., and stays compact at the same time.
The code sample at the link returns the rightmost point; you need to replace
>with>=on thenums[guess] > checkline to get the leftmost point. This saves you potentially costly backward linear search, or using a “backward”Comparator, which requires wrapping yourintintoIntegerobjects.