Kazi Rahamatullah
Kazi Rahamatullah
AboutProjectsBlogContact
UsesBooks
ResumeView CV
Kazi Rahamatullah

© Copyright 2026 Kazi Rahamatullah

AboutProjectsBlogBooksUses
Twitter/XGitHubProduct HuntCodeSandbox
Back to Blog
DSASearchBinary SearchAlgorithms

Binary Search — Algorithm Visualized

Learn binary search — halve sorted array each step, O(log n) lookup, lo/hi/mid visualizer, code breakdown, and common off-by-one pitfalls.

Jul 4, 20263 min read

Introduction

Binary search finds a target in a sorted array by comparing against the middle element and discarding half the search space each step — O(log n) time.

Quick index

#Section
1How it works
2Interactive visualizer
3Full implementation
4Complexity & pitfalls
5Real-life examples

1. How it works

plaintext
lo=0, hi=n-1
mid = (lo+hi)/2
if arr[mid] === target → found
if arr[mid] < target → lo = mid+1
else → hi = mid-1

Back to index


2. Interactive visualizer

Binary Search — Step Visualizer

Halve the search range each step — requires a sorted array.

Target: 23 · Start

2
5
8
12
16
23
38
45

Purple range = active search window

Binary search — sorted array required

const target = 23
let lo = 0, hi = n - 1
mid = floor((lo + hi) / 2)

Halve the search space each step — O(log n).

Time

O(log n)

Space

O(1)

Stable

—

Tip

Purple highlight = active search range. Each step eliminates roughly half the remaining indices.

Back to index


3. Full implementation

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

Function calls with output

js
// ── Demo calls — output shown on the right ──
const arr = [2, 5, 8, 12, 16, 23, 38, 45]
 
binarySearch(arr, 23) // → 5
binarySearch(arr, 2) // → 0
binarySearch(arr, 99) // → -1

Back to index


4. Complexity & pitfalls

MetricValue
TimeO(log n)
SpaceO(1) iterative
PrerequisiteSorted array

Warning

Off-by-one bugs — lo <= hi vs lo < hi, and mid + 1 / mid - 1 updates must match your invariant. Practice with the visualizer until the loop condition is automatic.

Interview Answer

"Can you binary search on a linked list?"

No — no O(1) random access to the middle element. Binary search requires indexed access (array) or a structure with similar O(1) midpoint lookup.

Back to index


5. Real-life examples

ScenarioWhy binary search
Dictionary / phone book lookupWords sorted alphabetically — open to middle, discard half
Git bisectFind commit that introduced bug — sorted history, halve each step
Price filter on sorted catalogProducts sorted by price — find first item ≥ budget
Autocomplete indexPrefix tree often backed by sorted string arrays
Database B-tree indexEach node splits sorted keys — binary search within node

E-commerce price filter

Products sorted by price — find first item at or above $50 budget.

A$10[0]
B$45[1]
C$55[2]
D$99[3]

Products sorted ascending by price.

Real-world implementation

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

function lowerBoundByPrice(products, minPrice) {
  let lo = 0, hi = products.length
  while (lo < hi) {
    const mid = Math.floor((lo + hi) / 2)
    if (products[mid].price < minPrice) lo = mid + 1
    else hi = mid
  }
  return lo < products.length ? products[lo] : null
}

Full working code for the scenario above.

Function calls with output

// ── Function calls with output ──
const products = [
  { name:"A", price:10 }, { name:"B", price:45 },
  { name:"C", price:55 }, { name:"D", price:99 }
]

Side output shows return value after each call — step through to trace execution.

Interview Answer

"Where have you used binary search outside interviews?"

Git bisect, searching sorted API pagination cursors, finding insertion point in sorted UI lists, and any indexed database query — all are binary search in disguise.

Back to index


Summary

Binary search turns sorted lookup from O(n) to O(log n) — foundation for binary search on answer, lower/upper bound, and rotated array variants.

Next reads: Linear Search · Big O Notation

Share this article

XLinkedInFacebook
Kazi Rahamatullah

Written by

Kazi Rahamatullah

FullStack Developer

X / TwitterGitHubLinkedIn

Subscribe to my newsletter

Stay up to date and get notified when I share new contents.

No spam ever, unsubscribe anytime