• Post Reply Bookmark Topic Watch Topic
  • New Topic

binarySearch(int[],key)  RSS feed

 
Arun Maalik
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 210
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Arun Maalik
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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".
 
Justin Fox
Ranch Hand
Posts: 802
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
would binary search be considered a "divide and conquer" method?

Justin
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Justin Fox:
would binary search be considered a "divide and conquer" method?


Yes.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!