File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 EJB 3 in Action this week in the EJB and other Java EE Technologies 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
 
Similar Threads
binary search
method overloading
Is there an "existence" binary search in the API
why collections.binarysearch() returns wrong output for 1st 2 index position ?
How do I search this Vector or String ?