arrays - default java util binary-search returns wrong results -
this question has answer here:
- array.binarysearch returning wrong data 2 answers
i got strange behavior binary search in java util
this code
public static void main (string[] args) throws java.lang.exception { // 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 values every element in array index
but works fine elements expect second 1
the returned values
0=========-1 -5=========6 2=========3 3=========4 4=========7 3=========4 i tested on java 7 , java 8 , gave me same results
you can test online on https://ideone.com/7wmfgg
if read javadoc of binarysearch you'll see array must sorted :
/** * searches specified array of longs specified value using * binary search algorithm. array must sorted (as * {@link #sort(int[])} method) prior making call. if * not sorted, results undefined. ...
Comments
Post a Comment