Java: want binary search of subset of an array

binary-search, java

Solution

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+.

Problem

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.

Original source