3

In Java, Arrays.binarySearch always searches the entire array. Sometimes part of the array has not been filled. Is there any function to search a part of the array, e.g.

int binarySearch(int[] a, int end, int value)

Yes, I could just use a TreeMap<Integer> but I have a lot of these and TreeMap<Integer> uses several times more memory than int[].

And yes, I can certainly write a binary search, but given the presence of Arrays.binarySearch it seems I shouldn't have to write my own.

1 Answer 1

10

There is an overloaded Arrays.binarySearch() that does exactly this:

public static int binarySearch(int[] a,
                               int fromIndex,
                               int toIndex,
                               int key)

It is available in Java 1.6+.

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

2 Comments

Oh duuuuuh! For some reason Google 'Java X' always presents old doc first. Now I feel silly for asking. If I could downvote my own question, I would.
@kevincline: You are quite right about Google and old Java docs. I usually search for java6 or java7, e.g. Arrays java6.

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.