Question

I'm trying to search value in an int array using Arrays.binarySearch(), and i know that if value would find in array this method returns value's index number and if array doesn't include value method returns a negative number.

Here is my array:

int[] searchInArray=new int[6];
searchInArray = new int[]{2,3,4,22,1,2};

And here is my code:

int result1=Arrays.binarySearch(searchInArray,55);
int result2=Arrays.binarySearch(searchInArray, 22);

When I run this code I get return1=-7 and return2=-7.

Then I try to find 1 instead of 22 then result2 being "-1".

Where am I making mistake?

Was it helpful?

Solution 2

You need to ensure that the array has been sorted before attempting to use a binary search. The following code should work as you expect:

    int[] searchInArray = new int[6];
    searchInArray = new int[] { 2, 3, 4, 22, 1, 2 };

    Arrays.sort(searchInArray);
    final int result1 = Arrays.binarySearch(searchInArray, 55);
    final int result2 = Arrays.binarySearch(searchInArray, 22);

    System.out.println("result1 " + result1);
    System.out.println("result2 " + result2);

Also you shouldn't be expecting the return -1. Arrays.binarySearch returns a negative number to indicate where the value should be inserted. From the javadoc:

index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.

OTHER TIPS

The prerequisite to use binarySearch() is that the array must be sorted. Yours is not.

Quote from the javadoc:

Searches the specified array of ints for the specified value using the binary search algorithm. The array must be sorted (as by the sort(int[]) method) prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found.

(emphasis mine)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top