Binary Search in Java: Explanation & Practice

Find target in sorted array

Problem summary

Given a sorted array and target value, return the index of target, or -1 if not found. Implement classic binary search.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] nums = {-1, 0, 3, 5, 9, 12};
        int target = 9;
        
        // left = 0, right = n-1
        // mid = left + (right - left) / 2
        // Adjust bounds based on comparison
        // Print: Index: 4
    }
}

Expected output and test cases

  • 9 found at index 4
    Index: 4
  • 2 not found
    Index: -1
  • First element
    Index: 0

Hints

  1. Use left + (right - left) / 2 to avoid overflow
  2. If nums[mid] == target, return mid
  3. If nums[mid] < target, search right half: left = mid + 1
  4. If nums[mid] > target, search left half: right = mid - 1

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler