Skip to Content

Binary Search

Binary Search is an efficient divide-and-conquer algorithm used to find the position of a target value within a sorted array. It works by repeatedly dividing the search range or interval in half until the target value is found or the search range is empty.

There are some key requirements for Binary Search to work effectively:

  • The array must be sorted in ascending or descending order.
  • Random access to elements is required (i.e., the data structure should allow direct access to any element by its index, like an array, not a linked list).
  • The data is static (not frequently changing), as frequent insertions or deletions would require re-sorting the array.

Now, you need to remember that Binary Search cannot apply to unsorted data structure, as if the data is not sorted, it will lead to incorrect results.

How it works?

Basically, we will initialize two pointers or indices to represent the current search range within the array:

  • left or low - pointing to the start of the array (index 0)
  • right or high - pointing to the end of the array (index length - 1)
  • mid - pointing to the middle element of the current search range (left + right) / 2

We will use mid value to compare with the target value. If the mid value is equal to the target value, we have found the target and return its index. If the mid value is less than the target value, we know that the target must be in the right half of the array, so we update the left pointer to mid + 1. If the mid value is greater than the target value, we know that the target must be in the left half of the array, so we update the right pointer to mid - 1. We repeat this process until we either find the target or the search range becomes empty (i.e., left exceeds right).

I will explain in detail in the implementation section below.

Why it’s so fast?

If we spoke why Binary Search is so fast compared to Linear Search, assuming we have a sorted array of 1,000,000 elements and we want to find a specific element.

In Linear Search, in the worst case, we might have to check each element one by one until we find the target or reach the end of the array. This means we could potentially make up to 1,000,000 comparisons.

But in Binary Search, we start by checking the middle element of the array. If the middle element is not the target, we can eliminate half of the array from consideration based on whether the target is less than or greater than the middle element. This halving (reduction by half) continues with each comparison.

Visual Analogy

Image you have a phone book with 1024 pages and you want to find a specific name. Instead of starting from page 1 and checking each name one by one (like Linear Search), you can open the book to the middle page (page 512) and see if the name you’re looking for is before or after that page.

  • 1st guess: Page 512
  • 2nd guess: Page 256 or 768 (depending on whether the name is before or after page 512)
  • 3rd guess: Page 128, 384, 640, or 896
  • 10th guess: You will find the name within 10 guesses because each guess effectively halves the number of pages you need to consider.

So, you only need 10 guesses to search through 1024 pages.

Implementation

In this variation, you’re given a sorted array and a target value. The goal is to find whether the target exists in the array and return its index.

binary_search.py
def binary_search(arr: list, target: int) -> int: left, right = 0, len(arr) - 1 while left <= right: mid = (left + right) // 2 if target > arr[mid]: left = mid + 1 elif target < arr[mid]: right = mid - 1 else: return mid return -1 arr = [1, 2, 3, 4, 5] target = 4 result = binary_search(arr, target) if result != -1: print(f"Target {target} found at index: {result}") else: print(f"Target {target} not found")

Let’s search for target value 4 in the sorted array [1, 2, 3, 4, 5].
Step 1:

Index: 0 1 2 3 4 Array: [1, 2, 3, 4, 5] ↑ ↑ ↑ left mid right

mid = (0 + 4) // 2 = 2 -> arr[2] = 3 < 4 -> move left

Step 2:

Index: 0 1 2 3 4 Array: [1, 2, 3, 4, 5] ↑ ↑ ↑ left mid right

mid = (3 + 4) // 2 = 3 -> arr[3] = 4 == 4 -> found at index 3

Visualization

Binary Search Visualization
10
[0]
20
[1]
30
[2]
40
[3]
50
[4]
Comparisons: 0
Idle
In Range
Checking
Found
Not Found
L = LeftM = MidR = Right
Search Controls
Algorithm Info

Binary Search

Binary Search is an efficient algorithm for finding a target value in a sorted array. It works by repeatedly dividing the search interval in half, comparing the middle element with the target, and eliminating half of the remaining elements.

Time Complexity

  • Best Case: O(1) - Element found at middle
  • Average Case: O(log n) - Halves search space each time
  • Worst Case: O(log n) - Element at end or not present

Space Complexity

O(1) - No extra space required (iterative)

Requirements

The array must be sorted. Binary search is much faster than linear search for large datasets.

Last updated on