Searching & Sorting AlgorithmsBeginner LevelStudy Time: 15 mins

Binary Search Algorithm

Binary Search is an efficient Divide and Conquer search algorithm over sorted arrays that repeatedly cuts the search interval in half, achieving O(log N) lookup speed.

Loading visualizer workspace...

Binary Search Halving Trace

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

Step 1 - Initial Midpoint Calculation

low = 0, high = 9 -> mid = Math.floor((0 + 9) / 2) = 4. Compare arr[4] (16) with target 23.

arr[mid] = 16 < 23 -> Target must be in right half [5..9]. Set low = mid + 1 = 5.
Eliminates left 5 elements instantly in one check.
Step 2

Step 2 - Second Midpoint Calculation

low = 5, high = 9 -> mid = Math.floor((5 + 9) / 2) = 7. Compare arr[7] (56) with target 23.

arr[mid] = 56 > 23 -> Target must be in left sub-half [5..6]. Set high = mid - 1 = 6.
Search range narrowed down to 2 elements.
Step 3

Step 3 - Final Target Match

low = 5, high = 6 -> mid = Math.floor((5 + 6) / 2) = 5. Compare arr[5] (23) with target 23.

arr[mid] = 23 == 23 -> Target found at Index 5!
Target located in just 3 comparison steps out of 10 elements.

Real-world analogy: Dictionary Page Halving

Precondition
Midpoint
Hover over items for details

Opening a dictionary to the middle page. If your word comes alphabetically before the middle word, you eliminate the entire right half.

  • Precondition= Dataset MUST be sorted.
  • Midpoint= mid = low + (high - low) / 2.

Complexity analysis

Scenario Simulator: Dataset Size (N = 500)
Presets:
N = 10N = 10,000
Complexity Curve MapBinary Search: O(log N) Logarithmic Time
Time (t)Size N (500)N = 500O(N²)O(N log N)O(N)O(log N)O(1)Binary Search Ha
Time Steps (N=500)

~9 steps (Logarithmic)

O(log N) Logarithmic Time

Space Footprint

O(1) Constant Space

Memory growth rate as N expands.

Performance Rank
Optimal Tier

Relative efficiency rating for large N.

OperationTime ComplexitySpace Complexity
Best CaseO(1)O(1)
Average CaseO(log N)O(1)
Worst CaseO(log N)O(1)

Code implementations

function binarySearch(arr, target) {
  let low = 0, high = arr.length - 1;
  while (low <= high) {
    const mid = Math.floor(low + (high - low) / 2);
    if (arr[mid] === target) return mid;
    if (arr[mid] < target) low = mid + 1;
    else high = mid - 1;
  }
  return -1;
}

Real-world applications

Case 01

Database B-Tree Indices

Locates primary key rows rapidly.

Case 02

Git Bisect

Finds the exact commit that introduced a bug via binary search over commit history.

Interview questions

Topic Knowledge Test & Assessment

10 Questions Assessment

Binary Search Algorithm Mastery Test

Test your mastery over Divide & Conquer search bounds, midpoint calculations, and log N runtime limits.