Reputation: 99
Recently I am working on arrays in Java and I needed to use the method binarySearch(arr, v)
in Arrays class to search the index of value v
in the array arr
if found.
Then I do some tests with some different arrays. When I try to search value 4
in the array {4, 3, 2, 1}
I found -5
.
Would someone can explain that please ?
You can check here http://tpcg.io/kibBmw
The code is below:
int[] arr = {4, 3, 2, 1};
System.out.println(Arrays.binarySearch(arr, 4));
-5
Upvotes: 0
Views: 69
Reputation: 302
For using standard binary search algorithm your input array must be in increasing value order otherwise you will get unexpected results.
Upvotes: 0
Reputation: 26076
Just look at the javadoc. You need to have a sorted array to use this method. You can do the following:
Arrays.sort(arr);
Arrays.binarySearch(arr, 4)
Upvotes: 1
Reputation: 6300
You should do Arrays.sort(arr);
before the binary search. From the documentation for Arrays.binarySearch
:
Searches the specified array of ints for the specified value using the binary search algorithm. The array must be sorted (as by the sort(int[]) method) prior to making this call. If it is not sorted, the results are undefined.
Upvotes: 3