Two Laptop Bag
The moose likes Beginning Java and the fly likes binarySearch(int[],key) Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "binarySearch(int[],key)" Watch "binarySearch(int[],key)" New topic
Author

binarySearch(int[],key)

Arun Maalik
Ranch Hand

Joined: Oct 25, 2005
Posts: 216
import java.util.Arrays;

class first{
public static void main(String[] args){
int arr[]={8,5,8,0,8,6,8,9,10};

int n=Arrays.binarySearch(arr,8);

System.out.println(n);


}
}

Daer sir in the above code i m searching number 8 in specified array but it is returning 4 why? although number 8 is on oth location also.

with regard

Arun kumar maalik
Aum Tao
Ranch Hand

Joined: Feb 14, 2006
Posts: 210
The arrays must be sorted before making this call, or else you will get undefined results.

Also, if the arrays contains multiple elements with the specified value, there is no guarantee which one will be found.

You can get more info in the Java docs.


SCJP 1.4 85%
Arun Maalik
Ranch Hand

Joined: Oct 25, 2005
Posts: 216
Thanks sir . JavaRanch is raely realy raely a very nice site of java reader.

with regard

Arun kumar maalik
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Read a little more on Binary Search to see why the array must be sorted. It works just as you probably would if I said "Guess a number between 1 and 100".


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Justin Fox
Ranch Hand

Joined: Jan 24, 2006
Posts: 802
would binary search be considered a "divide and conquer" method?

Justin


You down with OOP? Yeah you know me!
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24057
    
  13

Originally posted by Justin Fox:
would binary search be considered a "divide and conquer" method?


Yes.


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: binarySearch(int[],key)
 
Similar Threads
Can't figure out what's wrong with this method
here is a question and i have a very similar code but i need to convert it
ArrayIndex in Arrays
Mock Question -Array again!
fields of visibility