Search code examples
javaarraysbinary-search

Java Arrays.binarySearch not finding first value


I need to check an int[] to contain a certain value. The array will always be sorted.

I found a method that is simple enough, but I can't get it to work properly.

When i do:

int[] numbers=new int[] {6,8,15,16,18,19,25,26,28,29,32};
        for(int i=0;i<40;i++) {     
            int a= (Arrays.binarySearch(numbers, i));
            if (a>0)
            {
                System.out.println("Found: "+i);
            }   
        }

the output is:

Found: 8
Found: 15
Found: 16
Found: 18
Found: 19
Found: 25
Found: 26
Found: 28
Found: 29
Found: 32

If i add a zero at the start of the array, then it finds the 6 (but not the zero).

Why is the first entry in my array never found?


Solution

  • 0 = first position. As in, 'yes, I found your item; it is at the very front of the array'.

    a negative number means: Not found (and if remove the sign and subtract 1 you have the location where it would have to be inserted to keep the array sorted). You're checking for 'more than 0'; you should be checking for 'more than -1'.