aspose 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
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: About binarySearch throu arrays or Lists