Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Arrays.binary search returns wrong data even when array is sorted

Tags:

java

The documentation writes that "Arrays.binarySearch return a.length if all elements in the array are less than the specified key." So in the following program, I am expecting the value 4 to be printed but it prints -4. Why this anomalous behaviour?

import java.io.*;
import java.math.*;
import java.util.*;
import java.lang.*;

public class Main{ 
    public static void main(String[] args)throws java.lang.Exception{
        int[] a = new int[3];
        a[0] = 3;
        a[1] = 8;
        a[2] = 9;
        System.out.println(Arrays.binarySearch(a, 15));         
    }
}

1 Answers

Quoting from Java Docs..

Returns: index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1).

where the insertion point is

defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key

In your example, all elements are less than 15 and length of the array is 3. So the insertion point is 3 and therefore binarySearch returns -3-1 = -4.

like image 52
vidit Avatar answered Dec 16 '25 20:12

vidit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!