This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Java in General and the fly likes About binarySearch throu arrays or Lists Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "About binarySearch throu arrays or Lists" Watch "About binarySearch throu arrays or Lists" New topic
Author

About binarySearch throu arrays or Lists

Vadim Vararu
Ranch Hand

Joined: Jan 03, 2009
Posts: 147
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.
Vadim Vararu
Ranch Hand

Joined: Jan 03, 2009
Posts: 147
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).
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

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.

Details about the binary search algorithm here.


[My Blog]
All roads lead to JavaRanch
 
wood burning stoves
 
subject: About binarySearch throu arrays or Lists