This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Binary Search Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Binary Search" Watch "Binary Search" New topic
Author

Binary Search

Pawan Arora
Ranch Hand

Joined: Sep 14, 2008
Posts: 105

I don't know why in the above programme the result of binary search is -2. Any reason?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19557
    
  16

You'll need to sort the array first. Binary search by definition works only on sorted arrays. This is because of the way it searches for elements:

1) start at the center
2) check the current element
3)
a) if equal then done
b) if smaller then all previous elements are smaller; get the binary search of the second half of the array
c) if larger then all next elements are larger; get the binary search of the first half of the array

In the end the first / second half of the array will be only one element and the recursion can end.
[ November 23, 2008: Message edited by: Rob Prime ]

SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Binary Search
 
Similar Threads
Doubt using E.L with HashMap
Implement methods for Iterator using Generics for TreeSet
Sorting by 3 variables dynamically in arrayList
Iterating over an unknown number of vectors
binary search algorithm encoding?