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
- Start with Sorted values 1, 3, 5
- Do this Search for 3
- Result Index 1
Apply it to a real problem
- Start with Available sizes 2, 5 and 9
- Do this Search for 5 and then 7
- Result Found at 1, insert at 2
Advertisements
Run the example
Save as Main.java and run java Main.java with JDK 21.
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));
}
}
}
found at 1 insert at 2