0

I got very strange behavior from binary search in java util

this code

public static void main (String[] args) throws java.lang.Exception
{
    // your code goes here
     int[] A={-1, 6, 3, 4, 7, 4} ;

     for(int i=0;i<A.length;i++)
     {
         System.out.println(Arrays.binarySearch(A,A[i])+"========="+A[i]);
     }
}

should display all values every element in the array with its index

but it works fine for all elements expect the second one

the returned values are

0=========-1
-5=========6
2=========3
3=========4
4=========7
3=========4

I tested it on java 7 and java 8 and it gave me the same results

you can test online on https://ideone.com/7wMFgG

1
  • Are you aware that Binary search works on sorted arrays only? Commented Apr 24, 2015 at 18:23

1 Answer 1

4

If you read the Javadoc of binarySearch you'll see that the array must be sorted :

/**
 * Searches the specified array of longs for the specified value using the
 * binary search algorithm.  The array must be sorted (as
 * by the {@link #sort(int[])} method) prior to making this call.  If it
 * is not sorted, the results are undefined.
...
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.