Binary Search
in Java
Master the divide-and-conquer strategy that finds elements in a sorted array with \( O(\log n) \) efficiency: conceptually and with Arrays.binarySearch.
What Is Binary Search?
Binary search is an algorithm that finds a target value inside a sorted array by repeatedly cutting the search space in half. Instead of checking every element, it asks: "Is the target in the left half or the right half?"
Why Speed Matters
The Key Prerequisite
Binary search only works on sorted data. If the array is not sorted, the algorithm cannot reliably decide which half to discard, and it may return incorrect results.
The Algorithm Step by Step
Visual Walkthrough
Searching for target = 23 in the sorted array below:
Time Complexity Analysis
Linear vs Binary Search
| Linear Search | Binary Search | |
|---|---|---|
| Requires Sorting? | No | Yes |
| Time Complexity | \( O(n) \) | \( O(\log n) \) |
| \( n = 1{,}024 \) (max steps) | 1,024 | 11 |
| \( n = 1{,}000{,}000 \) (max steps) | 1,000,000 | 20 |
| Best For | Small or unsorted data | Large sorted datasets |
How to Apply Binary Search
Writing It Yourself
Using Arrays.binarySearch
Example 1: Finding a Score
A teacher stores sorted test scores: {55, 62, 74, 81, 88, 93, 97}. Does a student with score 88 exist?
Example 2: Target Not Found
Search for 70 in the same scores array: {55, 62, 74, 81, 88, 93, 97}.
Example 3: String Arrays
Arrays.binarySearch also works on String arrays (sorted lexicographically).
Common Mistakes
Summary at a Glance
| Concept | Detail |
|---|---|
| Prerequisite | Array must be sorted |
| Time Complexity | \( O(\log n) \) |
| Space Complexity | \( O(1) \) iterative, \( O(\log n) \) recursive |
| Java Built-in | Arrays.binarySearch(arr, key) |
| If Found | Returns the index (non-negative) |
| If Not Found | Returns \( -(insertion\text{ }point) - 1 \) |
| Safe Midpoint | \(\texttt{low} + (\texttt{high} - \texttt{low}) / 2\) |
Question 1 of 5
What is the most important prerequisite for binary search to work correctly?
Question 2 of 5
What is the worst-case time complexity of binary search on an array of \( n \) elements?
Question 3 of 5
Given int[] arr = {10, 20, 30, 40, 50}, what does Arrays.binarySearch(arr, 35) return?
Question 4 of 5
Why is low + (high - low) / 2 preferred over (low + high) / 2 when computing the midpoint?
Question 5 of 5
In a hand-written binary search, what happens if you use \(\texttt{while (low < high)}\) instead of \(\texttt{while (low <= high)}\)?