posted 16 years ago
A binary search requires elements to be sorted. 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.
As you can see, if the elements are not sorted before the binary search is performed, then the results will be unpredictable, because each decision about whether to narrow the search to the first or second half will not have a basis.
[ July 31, 2007: 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