There is an afirmation in SCJP preparation book: "To be searched (via binarySearch method), an array or a List must first be sorted".
Tell me, please, why do i have to sort firstly the list in order to search via binarySearch method?
Thanks, Vadim Vararu.
If you think you've done too much, usually it means you've done too few.
Joined: Jan 03, 2009
Ok, i've searched it and found that it is necessary because the algorithm of binary search can be applied only on sorted lists (arrays).
The algorithm used in the binarySearch assumes that the array is sorted. This is a precondition. This is how some sorting algorithms work. Searching for items in a collection is often more efficient when the collection is properly sorted.