File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Problem in binarySearch() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Problem in binarySearch()" Watch "Problem in binarySearch()" New topic

Problem in binarySearch()

Rizwan Qadri
Ranch Hand

Joined: May 28, 2007
Posts: 40
Hi, All,

I fail to understand the O/P of this program. Whatever string i passed in BinarySearch(), its giving me O/P as 1. Please help

import java.util.*;
class ComparatorTest implements Comparator

static String[] sa = { "d", "bbb", "aaaa" };

public int compare(Object o1, Object o2)
int s1 = ((String) o1).length();
int s2 = ((String) o1).length();
return s1 - s2;
public static void main(String[] args)
System.out.println(Arrays.binarySearch(sa, "d",new ComparatorTest()));
Alexsandra Carvalho
Ranch Hand

Joined: Jul 13, 2007
Posts: 75

int s2 = ((String) o1).length();

I think you would to say:

int s2 = ((String) o2).length();

Rizwan Qadri
Ranch Hand

Joined: May 28, 2007
Posts: 40
No, What i want to say in "(Arrays.binarySearch(sa, "d",new ComparatorTest()));
" .In this whatever string i passes , be it "d","dd",or "ddd", O/P is 1. Why?
prajal Mehta
Ranch Hand

Joined: Dec 03, 2007
Posts: 66

change the line2 to int s2= ((String o2).length();
I guess, because you are comparing length of object o1 to itself ,the output of binary search is unpredictable!
Jari Timonen
Ranch Hand

Joined: Jan 16, 2004
Posts: 230
Alexandra's reply is correct... What do you want to archive? If you change the code, List will be sorted in length order.

SCJP 5.0, SCJD URLyBird 1.3.3, OCMJEA 5 (SCEA) Factory Homes
Shaili Merchant

Joined: Nov 20, 2007
Posts: 27
Don't we require to sort the array prior to searching according to pg no 557 of K&B book ???Otherwise it gives unpredictable results

Or is it that this is not applicable in the above code because it is already sorted??
[ December 12, 2007: Message edited by: Shaili Merchant ]
Rizwan Qadri
Ranch Hand

Joined: May 28, 2007
Posts: 40
i am still confused.If i changed "int s2 = ((String) o1).length();" to "int s2 = ((String) o2).length();", i get result -4 for every string i passed.
I agree. Here's the link:
subject: Problem in binarySearch()
Similar Threads
Sorting ArrayList
Comparable/Comparator query
BinarySearch Doubt
equal(Object o) doubt