This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
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 ]
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Joined: Nov 10, 2006
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...