GoAlgo

GoAlgo

Binary Search

Search Algorithm

Binary Search

Binary Search efficiently finds a target value in a sorted array by repeatedly dividing the search interval in half.

No data to display.
Deep Dive

Understanding Binary Search in Detail

Binary Search is one of the most elegant and efficient searching algorithms in Computer Science. It works on the principle of divide-and-conquer, repeatedly halving the search space until the target is found. This approach makes it dramatically faster than Linear Search for large, sorted datasets.

Imagine looking up a word in a physical dictionary. You would not start at page one and read every entry—that would take forever! Instead, you open the dictionary roughly in the middle. If your word comes before the page you opened, you focus on the first half; if it comes after, you focus on the second half. You keep halving until you find your word. This is exactly how Binary Search works.

The Logic Behind Divide and Conquer

The core mechanism of Binary Search relies on eliminating half of the remaining elements with each comparison.

  • Prerequisite: The array must be sorted in ascending (or descending) order.
  • Initialize: Set two pointers:left = 0right = n - 1
  • Calculate Mid: Find the middle index:mid = (left + right) / 2
  • Compare: Ifarr[mid] == target, the search is complete—return mid.
  • Narrow Left: Ifarr[mid] < target, the target is in the right half. Set left = mid + 1.
  • Narrow Right: Ifarr[mid] > target, the target is in the left half. Set right = mid - 1.
  • Repeat: Continue until left > right, which means the target is not in the array.

Step-by-Step Algorithm Trace

Let's trace the algorithm searching for value 23 in a sorted array.

Input Array: [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
Target: 23

Iteration 1: Full Array

  • Search range: left = 0, right = 9
  • Calculate mid: mid = (0 + 9) / 2 = 4
  • Compare: arr[4] = 16 vs target 23
  • 16 < 23 — Target is in the right half.

Eliminate indices 0-4. New range: [5, 9]

Iteration 2: Right Half

  • Search range: left = 5, right = 9
  • Calculate mid: mid = (5 + 9) / 2 = 7
  • Compare: arr[7] = 56 vs target 23
  • 56 > 23 — Target is in the left half.

Eliminate indices 7-9. New range: [5, 6]

Iteration 3: Narrowed Down

  • Search range: left = 5, right = 6
  • Calculate mid: mid = (5 + 6) / 2 = 5
  • Compare: arr[5] = 23 vs target 23
  • 23 = 23 — Match found!

Target found at index 5. Return 5. Only 3 comparisons needed for 10 elements!

Code Implementation

Below is the implementation of Binary Search in multiple programming languages. Both iterative and recursive approaches are commonly used.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <stdio.h>
int binarySearch(int arr[], int n, int target) {
int left = 0;
int right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target)
return mid; // Element found
if (arr[mid] < target)
left = mid + 1; // Search right half
else
right = mid - 1; // Search left half
}
return -1; // Element not found
}
int main() {
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 10;
int result = binarySearch(arr, n, target);
if (result == -1)
printf("Element not found");
else
printf("Element found at index %d", result);
return 0;
}
C35 lines.c

Time & Space Complexity Analysis

Binary Search is remarkably efficient, making it a go-to algorithm for searching in sorted collections.

Time Complexity

O(log n)Worst Case

Even in the worst case, Binary Search only needs log₂(n) comparisons. For an array of 1 million elements, this means at most 20 comparisons—compared to 1 million for Linear Search!

O(log n)Average Case

On average, the algorithm performs about log₂(n) - 1 comparisons, which is still O(log n).

O(1)Best Case

If the middle element happens to be the target on the first check, the search completes in constant time.

Space Complexity

O(1)Constant Space (Iterative)

The iterative version uses only a few variables regardless of input size. The recursive version uses O(log n) space due to the call stack, but this is still very efficient.

When to Use Binary Search?

Binary Search is the preferred algorithm whenever you are working with sorted data and need fast lookups.

Large Sorted Datasets

Binary Search excels when searching through millions of sorted records. Database indexes, phone directories, and sorted file systems all rely on binary search principles.

Finding Boundaries

Variations like "lower bound" and "upper bound" binary search are used to find the first or last occurrence of a value, or to find insertion points in sorted arrays.

Optimization Problems

Binary search on the answer space is a powerful technique for solving optimization problems where you need to find the minimum or maximum value satisfying certain conditions.