Binary Search in Java: Explanation & Practice

Implement binary search on sorted array

Problem summary

Write a program that implements binary search on a sorted array.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] arr = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
        int target = 23; // Test case 1
        
        // Implement binary search
        // Print: Found at index: <index> OR Not found
    }
}

Expected output and test cases

  • Find 23
    Found at index: 5
  • Find first element
    Found at index: 0
  • Element not in array
    Not found

Hints

  1. Maintain low and high pointers
  2. Calculate mid and compare with target
  3. Narrow search range each iteration

Related Arrays exercises

Practice all Arrays exercises · Run this idea in the Java compiler