7

I need to find all elements in sorted array with Arrays.binarySearch method. I want to iterate binary search in lowerbound = pos + 1 (pos is previous match), but binarySearch is not guaranteed to return first match (min match index)?

How can I make this?

1 Answer 1

9

You can easily use the result of binarySearch to get all the matches :

long[] sortedArr = ...
int index = Arrays.binarySearch (sortedArr, value);
int first = index;
int last = index;
if (index >= 0) {
    while (first > 0 && sortedArr[first-1] == value)
        first--;
    while (last < sortedArr.length - 1 && sortedArr[last+1] == value)
        last++;
}

After you run this code, the indices between first and last (inclusive) are all the indices that contain the searched value.

Sign up to request clarification or add additional context in comments.

2 Comments

I make it like you. Just I want know, maybe I can iterate this in 'one-line' style.
looping without braces won't pass code review around here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.