Java Binary Search — Free Java Tutorial
Learn Java Binary Search in Java with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.
TL;DR: Learn Java Binary Search in Java with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.
Written & reviewed by the Syllab.in Academic Team (CBSE/NCERT subject experts) · Updated
Java Binary Search in Java
Binary search finds an element in a sorted array in O(log n) time by repeatedly halving the search space. Compare the middle element with the target: if equal, found; if target is smaller, search left half; if larger, search right half.
Precondition: the array MUST be sorted. Binary search on an unsorted array produces incorrect results.
Iterative and recursive implementations both achieve O(log n) time. Iterative uses O(1) space; recursive uses O(log n) stack space.
Java provides Arrays.binarySearch(arr, target) and Collections.binarySearch(list, target) for sorted arrays and lists.
Java Binary Search — Syntax
// Iterative binary search
int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2; // avoids overflow
if (arr[mid] == target) return mid;
if (arr[mid] < target) left = mid + 1;
Learn Java Binary Search step by step with Syllab's free interactive Java tutorial — runnable code examples, practice exercises and instant AI feedback, all free with no signup. Explore the full Java course →