Binary Search Visualizer
Visualize binary search algorithm step by step
Updated
What is the Binary Search Visualizer?
The Binary Search Visualizer is an interactive, step-by-step educational tool designed to help you understand how the binary search algorithm operates.
Whether you are a computer science student preparing for exams, a developer brushing up on algorithms for coding interviews, or a curious learner, this tool provides deep insight into the mechanics of efficiently searching sorted arrays.
Key Features
- Step-by-Step Animation: Control the execution with play, pause, next, and previous buttons to analyze each comparison at your own pace.
- Pointer Tracking: Clearly highlights the
lo(low),mid, andhi(high) pointers, showing exactly how the search range narrows down with each iteration. - Search Modes: Supports finding the "any", "first", or "last" occurrence of a target value in arrays containing duplicates.
- Synced Pseudocode: Watch the algorithm's logic unfold alongside the executing line of pseudocode.
- Performance Metrics: Tracks the number of comparisons and iterations, and directly compares them against a linear search to demonstrate the efficiency.
- Custom Inputs: Input your own sorted arrays (up to 120 elements) or use our built-in presets to explore different scenarios instantly.
How it works
Binary search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until you've narrowed down the possible locations to just one.
The Algorithm Steps
- Initialize Pointers: Start with two pointers,
lo = 0(the beginning of the array) andhi = array.length - 1(the end). - Calculate Middle: Find the middle index:
mid = lo + Math.floor((hi - lo) / 2). This specific formula prevents integer overflow that can occur in languages like Java or C++ if you simply do(lo + hi) / 2. - Compare: Compare the target value to the middle element,
array[mid]:
- If
array[mid] === target, you found the target! - If
array[mid] < target, the target must be in the right half. Updatelo = mid + 1. - If
array[mid] > target, the target must be in the left half. Updatehi = mid - 1.
- Repeat: Continue this process while
lo <= hi. - Not Found: If
loexceedshi, the search range is empty, meaning the target is not in the array. Return-1.
Handling Duplicates
The standard algorithm returns as soon as it finds a match. To find the first or last occurrence of a duplicated value, the algorithm is slightly modified:
- First Occurrence: When
array[mid] === target, record the index but continue searching the left half (hi = mid - 1) to see if an earlier duplicate exists. - Last Occurrence: When
array[mid] === target, record the index but continue searching the right half (lo = mid + 1) to find a later duplicate.
Complexity Analysis
- Time Complexity: — Because the search space is halved with every step, the number of comparisons grows logarithmically. An array of 1,000,000 items takes at most ~20 comparisons!
- Space Complexity: — The iterative version only requires a few variables to store pointers, requiring constant extra memory.
Examples
Finding a Target in a Sorted Array
Visualizing a standard binary search for the number 7 in an array of 10 elements.
Searching for the First Occurrence (Duplicates)
Using the "first occurrence" mode to find the starting index of a repeated number.
Target Not Present in Array
Observe how the algorithm eliminates halves until the search range is empty.
Frequently asked questions
Why does the array need to be sorted for Binary Search to work?
Why does the array need to be sorted for Binary Search to work?
Binary search relies on the assumption that the array is ordered. It determines which half to discard by comparing the target to the middle element. If the array is unsorted, there is no guarantee that discarding the left or right half will safely remove only values that are strictly greater or smaller than the target, breaking the algorithm.
What is the difference between "Any", "First", and "Last" occurrence modes?
What is the difference between "Any", "First", and "Last" occurrence modes?
"Any" mode returns the index immediately as soon as the target is found. "First" mode continues searching the left half even after a match is found to ensure it locates the very first duplicate. "Last" mode continues searching the right half to locate the final duplicate of the target value.
How is the middle index calculated safely?
How is the middle index calculated safely?
The middle index is calculated using mid = lo + Math.floor((hi - lo) / 2). While Math.floor((lo + hi) / 2) works mathematically, adding lo and hi together first can cause integer overflow in statically typed languages like Java or C++ if the array is massive. The subtraction-based formula is mathematically equivalent and safe from overflow.
What happens if the target is not in the array?
What happens if the target is not in the array?
The algorithm continues halving the search range. Eventually, the lo pointer will become greater than the hi pointer. At that exact moment, the loop condition (lo <= hi) evaluates to false, the loop terminates, and the algorithm returns -1 to indicate the target is not present.
Is Binary Search always faster than Linear Search?
Is Binary Search always faster than Linear Search?
Yes, for large sorted datasets, binary search is vastly faster because it operates in time, whereas linear search takes time. However, if the array is very small (e.g., less than 10-20 elements) or the data is completely unsorted, the overhead of sorting or the simplicity of a linear scan can sometimes make linear search practically comparable or faster.
Related tools
More utilities you might find handy.
Recursion Tree Visualizer
Visualize recursive call trees step by step
Regex Visualizer — Railroad Diagram Generator for Regular Expressions
Free online regex visualizer that renders any JavaScript regular expression as an interactive railroad diagram, with a plain-English breakdown, live match tester, and ReDoS warnings — all in your browser.
Shape Drawer
Create and edit geometric shapes with precise measurements, live calculations, and export to SVG, CSS, or HTML