LearnWithKiriti

Binary Search

đź’» Try it yourself first. Write your solution in Java, C++, Python or JavaScript and run it against hidden tests, right here. New: mock interview with Mr. Tock. Explain your approach out loud, he pushes you to improve it, then you code it. You get a scorecard at the end.
Play
On this page
  1. Revision notes
  2. Brute: Linear Search
  3. Optimal: Binary Search

Revision notes

Binary Search

Video: “Binary Search: cut the shelf in half” on LearnWithKiriti (Kodee). LeetCode 704.

Find the index of target in a sorted array of distinct numbers, or return -1. Example: [2, 5, 8, 12, 16, 23, 38, 56], target 23 -> 5

Folder Approach Time Extra space
Brute-LinearSearch/ Linear search: Linear search: check every number from the left. It ignores the one thing we were given: the array is sorted. O(n) O(1)
Optimal-BinarySearch/ Binary search: Look at the middle (mid). If target is bigger, it can only be right of mid (low = mid + 1); if smaller, left of it (high = mid - 1). Half the shelf is gone every step. O(log n) O(1)

Rebuild it

Sorted means one look rules out half. Compare the target with the middle (mid). Bigger: it can only be right of mid, so low = mid + 1. Smaller: high = mid - 1. Stop when low > high. Write mid = low + (high - low) / 2 so low + high never overflows.

See each folder’s pseudocode.md. Every program runs Example 1 and prints the answer; the same code is in the practice panel’s Start menu on learnwithkiriti.com, where Shelf Bot can act it out.

brute

Brute: Linear Search

Brute: linear search

Linear search: check every number from the left. It ignores the one thing we were given: the array is sorted.

for scan from 0 to size - 1:
    if nums[scan] == target:
        return scan
return -1

O(n): a million books, up to a million looks. It never uses the fact that the shelf is sorted.

BinarySearchBrute.java
import java.util.*;

public class BinarySearchBrute {
    public int search(int[] nums, int target) {
        for (int scan = 0; scan < nums.length; scan++) {
            if (nums[scan] == target) {
                return scan;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        BinarySearchBrute solver = new BinarySearchBrute();
        int[] nums = new int[]{2, 5, 8, 12, 16, 23, 38, 56};
        int target = 23;
        int answer = solver.search(nums, target);
        System.out.println(answer);
    }
}
optimal

Optimal: Binary Search

Optimal: binary search

Look at the middle (mid). If target is bigger, it can only be right of mid (low = mid + 1); if smaller, left of it (high = mid - 1). Half the shelf is gone every step.

low = 0
high = size - 1
while low <= high:
    mid = low + (high - low) / 2
    if nums[mid] == target: return mid
    if target > nums[mid]: low = mid + 1
    else: high = mid - 1
return -1

Dry run on Example 1:

Target 23 in [2, 5, 8, 12, 16, 23, 38, 56]:

low high mid nums[mid] move
0 7 3 12 23 > 12: low = 4
4 7 5 23 found: 5

O(log n): a million books need at most 20 looks. O(1) extra space.

BinarySearchOptimal.java
import java.util.*;

public class BinarySearchOptimal {
    public int search(int[] nums, int target) {
        int low = 0;
        int high = nums.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (nums[mid] == target) {
                return mid;
            }
            if (target > nums[mid]) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        BinarySearchOptimal solver = new BinarySearchOptimal();
        int[] nums = new int[]{2, 5, 8, 12, 16, 23, 38, 56};
        int target = 23;
        int answer = solver.search(nums, target);
        System.out.println(answer);
    }
}