Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem in binarySearch()

 
Rizwan Qadri
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In

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


I think you would to say:


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


Rigth?
 
Rizwan Qadri
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 232
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alexandra's reply is correct... What do you want to archive? If you change the code, List will be sorted in length order.
 
Shaili Merchant
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic