Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java arrays.binary search multiple matches?

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?

like image 291
user2010633 Avatar asked Mar 22 '15 11:03

user2010633


People also ask

Can binary search array have duplicates?

A binary search only gives you the position of the value you want, or the position of 1 of them if duplicated. To display all duplicates and indexes, you need to do a secondary search around the position returned by binary search routine.

Does binary search work with doubles?

Binary search works for integer arrays, but not for double arrays.

What does Java's arrays binarySearch () method return?

Simply put, the Arrays. binarySearch() method can look for a given element in a sorted array and return its index if found. Remember, the method returns the index of the found item and not the item itself.

Does array need to be sorted for binary search?

Binary search is faster than linear search except for small arrays. However, the array must be sorted first to be able to apply binary search. There are specialized data structures designed for fast searching, such as hash tables, that can be searched more efficiently than binary search.


1 Answers

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.

like image 55
Eran Avatar answered Oct 10 '22 09:10

Eran