Why is it returning -1 when when I search for 1 with binarySearch method in Collections class in java

Viewed 21

See this code:

package learningjava;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Java{

    public static void main(String args[]) {

        List obj = new ArrayList();
        obj.add(2);
        obj.add(4);
        obj.add(6);
        obj.add(1);

        int bs = Collections.binarySearch(obj,6);
        System.out.println(bs);
    
    }
}

Here I am using binarySearch method in Collections class. I am using it to find the position of 6 in this list. Here it is returning 2 which is correct.

But if I try to find the postion of 1 in this list it is returning -1.

 package LearningJava;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Java{

    public static void main(String args[]) {

        List obj = new ArrayList();
        obj.add(2);
        obj.add(4);
        obj.add(6);
        obj.add(1);

        int bs = Collections.binarySearch(obj,1);
        System.out.println(bs);
    
    }
}

The output is -1.

Why is it returning -1 instead of 3. The problem is only with 1. If I try to find the position of other numbers, it is working correctly.

2 Answers

As per binarySearch method , input List must be sorted according to natural order otherwise result will be undefined which is happening in your case.

Refer: https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#binarySearch(java.util.List,%20T)

Adding Collections.sort(obj) before below line will give the desired output.

int bs = Collections.binarySearch(obj,1);

Updated code:

 List obj = new ArrayList();
            obj.add(2);
            obj.add(4);
            obj.add(6);
            obj.add(1);
//Input list must be sorted as below
            **Collections.sort(obj);**

            int bs = Collections.binarySearch(obj,1);
            System.out.println(bs);
Related