Forums Register Login

binarySearch(int[],key)

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
Thanks sir . JavaRanch is raely realy raely a very nice site of java reader.

with regard

Arun kumar maalik
+Pie Number of slices to send: Send
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".
+Pie Number of slices to send: Send
would binary search be considered a "divide and conquer" method?

Justin
+Pie Number of slices to send: Send
 

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



Yes.
This one time, at bandcamp, I had relations with a tiny ad.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 809 times.
Similar Threads
Mock Question -Array again!
here is a question and i have a very similar code but i need to convert it
ArrayIndex in Arrays
Can't figure out what's wrong with this method
fields of visibility
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 08:30:13.