• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem on binarySearch

 
Bob CHOI
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My code below,



it printed out:

2 2
1 not found

if comment line #:

1 1
2 2


What would be the problem that one element couldn't have been found?

Thanks!

[ December 19, 2006: Message edited by: Bob CHOI ]

[ December 19, 2006: Message edited by: Bob CHOI ]

[ December 19, 2006: Message edited by: Bob CHOI ]
[ December 19, 2006: Message edited by: Bob CHOI ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you check the API documentation for binarySearch, you will see the "list must be sorted into ascending order ... prior to making this call. If it is not sorted, the results are undefined." Note that it's not enough for the list to be sorted -- it must be sorted in ascending order.

To understand why, consider how a binary search works. Basically, it looks at the element in the middle of the list and compares it to the element it's looking for. If that happens to what it's looking for, then it's done. Otherwise, based on the comparison -- and assuming that the list is sorted in ascending order -- it narrows the search to either the first half of the list or the second half of the list. For example, if I'm searching for "75" and the middle element is "50," then 75 (if present at all) must be in the second half of the list, so I can forget about the first half. This process repeats until the element is found or the list runs out of elements.

So if the list is not sorted in ascending order, then binary search results are unpredictable, because the determinations of whether to continue looking in the first half or the second half of the list have no basis.

Because your code uses a very small number of elements (just 1 and 2, added in that order), it's hard to see this pattern. Try adjusting your code to add more elements in different orders before sorting and/or searching.
[ December 19, 2006: Message edited by: marc weber ]
 
Bob CHOI
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Marc, thanks so much for such a nice concrete answer!

i was hurried, hadn't really grasp essence of Collection framework. hopefully do better once without time pressure...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic