This discussion is archived
5 Replies Latest reply: Jan 4, 2007 8:56 AM by 807599 RSS

Issues with Arrays.binarySearch(Object[], Object)

807598 Newbie
Currently Being Moderated
Hi,

I am trying to find a String in an array using Arrays.binarySearch(Object[], Object). I have sorted the array initially. However i am getting negative values even if the String value is present in the array.

Is it that with String values the above method gives errorneous results.

Has anybody faced a similar problem.

Regards
  • 1. Re: Issues with Arrays.binarySearch(Object[], Object)
    807598 Newbie
    Currently Being Moderated
    Which way do you sort your array?
    I have tried the next code and it works:
            String a1 = "a1";
            String a2 = "a2";
            
            String[] array = { "a5" , "a1", "a3"  };
            
            Arrays.sort(array);
            
            System.out.println(Arrays.binarySearch(array, a1));
            System.out.println(Arrays.binarySearch(array, a2));
  • 2. Re: Issues with Arrays.binarySearch(Object[], Object)
    807598 Newbie
    Currently Being Moderated
    I tried to do this in a small program and it seems to work fine.
    String strArr[]= {"a","e","d","c","b"};      
    Arrays.sort(strArr);
    System.out.println(Arrays.binarySearch(strArr,"d"));
    Above statement prints 3.
  • 3. Re: Issues with Arrays.binarySearch(Object[], Object)
    807599 Newbie
    Currently Being Moderated
    I tried this and it seems to be working only part of the time, not sure if I am using this incorrectly?
    import java.util.Arrays;
    
    class test { 
         public static void main(String[] args) {
              String[] names = new String[]{"BOB", "JOE", "JIMMY", "FRED"};
    
              for(String name : names){
                   System.out.println(name + " is at : " +
                        Arrays.binarySearch(names, name)
                   );
              }
         }
    }
    The above test returns:
    BOB is at : 0
    JOE is at : 1
    JIMMY is at : -2
    FRED is at : -2
  • 4. Re: Issues with Arrays.binarySearch(Object[], Object)
    807599 Newbie
    Currently Being Moderated
    This from the javadocs for the binarySearch method:

    Searches the specified array for the specified object using the binary search algorithm. The array must be sorted into ascending order according to the natural ordering of its elements (as by Sort(Object[]), above) prior to making this call. If it is not sorted, the results are undefined.

    If the source Array is not sorted the search is not reliable.
  • 5. Re: Issues with Arrays.binarySearch(Object[], Object)
    807599 Newbie
    Currently Being Moderated
    So you answered your own question? After bumping an old Thread?

    Congratulations!

    ~Tim