• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collections.binarySearch(...)

 
Deepak Chopra
Ranch Hand
Posts: 433
Eclipse IDE Firefox Browser Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I found the following conflicting problem:
according to k & B :
"if a collection/array you want to search was sorted using a Comparator,it must be searched using the same Comparator, which is passed as the second argument..."

Now I wrote a program:


Even though second time while searching I am passing only List and Object need to search..!! I was expecting some unexpecting behavior..!!
But I was shocked It gave me right answer ?

Can some one explain me..how binary search behave behind the codes!!

DVDInfo has two parameter : name and size..!!!
 
Alex Belisle Turcot
Ranch Hand
Posts: 516
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I read the API, and here's my opinion.

Using a distinct Comparator is similar to using an unsorted list. For that new comparator, the data is not correctly sorted.

In the API, for binarySearch, it says:
If it is not sorted, the results are undefined. If the list contains multiple elements equal to the specified object, there is no guarantee which one will be found.


The binarySearch compares the elements and relies on the order for its correctness. You'll just end up not finding the object your are looking for.

Regards,
Alex
[ January 23, 2008: Message edited by: Alex Belisle Turcot ]
 
Dean Jones
Ranch Hand
Posts: 129
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Sunny, can you please provide the full code, to make it clear.
 
Deepak Chopra
Ranch Hand
Posts: 433
Eclipse IDE Firefox Browser Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, There was some problem in my code I have corrected that, But still I have some confusion, Please help me to clear that :

1) I have created one list containing movie Object

Movie Object has two properties : Name and Size

2) I sorted out the list according to Movie name

3) I sorted out again on the base of size

4) There are some movies with equal size

5) Now I searched out one movie with unique name and non unique Size

6) First I did not pass the Comparator Object

7) result is correct position.

8) Now I pass the comparator Object, result is unexpected, Some strange positive integer.

9) Now I try to search a movie with unique size

10) first search without Comparator, Result is some negative integer as expected

11) Now I pass comparator Object, result is correct position.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic