This discussion is archived
4 Replies Latest reply: Dec 1, 2013 10:23 PM by 96491dde-8429-4baf-a153-8e33d9cfdb47 RSS

Why does the Collections.binarySearch() Method is unpredictable?

irshan Newbie
Currently Being Moderated

//Start of Code

import java.util.ArrayList;

import java.util.Collections;

import java.util.Scanner;

 

public class BinSea {

 

    private static Scanner s;

 

    public static void main(String[] args) {

 

        ArrayList<Integer> a = new ArrayList<>();

        a.add(1);

        a.add(2);

        a.add(5);

        a.add(7);

        a.add(4);

        a.add(8);

        System.out.println("The Complete Array List :" +a);

       

        s = new Scanner(System.in);

        int key = 1;

      

        while(key!=0)

        {

        System.out.print("Enter the Key to find : ");

        key = s.nextInt();

       

        int index=Collections.binarySearch(a, key, null);

 

          System.out.println(key +" is available at index: "+index);

        }

       

        System.out.println("Executed Successfully");

    }

}

 

 

//End of code

 

output:

The Complete Array List :[1, 2, 5, 7, 4, 8]

Enter the Key to find : 5

5 is available at index: 2         

Enter the Key to find : 7

7 is available at index: -6

Enter the Key to find : 0

0 is available at index: -1

Executed Successfully

 

Why is the Output for the Search key "7" is "-6" when it is present in the Array List (for sure the index should be 3).

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points