← Unit 4 · all exercises
Saved in this browser only

Binary search

The array is already sorted from smallest to largest. Return the position of the target, or -1 when it is absent. Halve the range each time rather than checking every item.

int search(int[] sorted, int target)

Solution.java
Loading editor…
Results

Examples

  • Solution.search(new int[]{1, 3, 5, 7, 9}, 7) → 3
  • Solution.search(new int[]{1, 3, 5}, 4) → -1

There are also 4 hidden tests you can't see. Solve the problem, not the examples.