Decode the insertion point of a missing key in Java

Search a sorted array for both a present and an absent quantity. For a missing key, the result encodes the first position at which that key could be inserted.

A simple example

Search for 3

  1. Start with Sorted values 1, 3, 5
  2. Do this Search for 3
  3. Result Index 1
Indices start at zero. Three is the second value.

Apply it to a real problem

  1. Start with Available sizes 2, 5 and 9
  2. Do this Search for 5 and then 7
  3. Result Found at 1, insert at 2
The missing size belongs between 5 and 9.
Advertisements

Run the example

Save as Main.java and run java Main.java with JDK 21.

Main.java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) throws Exception {
        int[] sizes = {2, 5, 9};
        for (int wanted : new int[]{5, 7}) {
            int result = Arrays.binarySearch(sizes, wanted);
            System.out.println(result >= 0 ? "found at " + result : "insert at " + (-result - 1));
        }
    }
}
Output
found at 1
insert at 2

Official Java documentation