How to use the Binary Search Visualizer
- 1. Enter a sorted arrayNumbers in ascending order, up to 64 of them.
- 2. Pick a targetAnd choose any match, first occurrence or last occurrence.
- 3. Step throughEach step greys out the half that was ruled out.
How binary search works
Binary search finds a value in a sorted array by checking the middle element and throwing away half of the range each time:
- Set low = 0 and high = n − 1.
- mid = (low + high) ÷ 2, rounded down.
- If arr[mid] equals the target, you're done. If it's smaller, search the right half (low = mid + 1); if it's larger, search the left half (high = mid − 1).
- If low passes high, the target isn't there, and low is where it would be inserted.
That makes at most ⌊log₂ n⌋ + 1 comparisons: 10 for 1,000 items and only 20 for a million. The first occurrence variant keeps searching left after a match, and last occurrence keeps searching right, which is how you count duplicates in O(log n).
Worked example
Array [2, 5, 8, 12, 16, 23, 38, 56, 72, 91], target 23:
- low 0, high 9, mid 4: value 16 < 23, so search the right half.
- low 5, high 9, mid 7: value 56 > 23, so search the left half.
- low 5, high 6, mid 5: value 23. Found at index 5.
That's 3 comparisons; the most this 10-item array could ever need is 4. A linear search would have checked 6 items. Search for 24 instead and you'll see low pass high, with the message that 24 would be inserted at index 6.
Watch for the classic bugs: forgetting to sort first, using while (low < high) when you need <=, and in languages with fixed-size ints, writing (low + high) / 2 where low + high can overflow. Use low + (high − low) / 2.
Frequently asked questions
Does the array have to be sorted?
Yes. The tool checks it and tells you which number is out of order.
What does 'lower bound' mean?
The first position where the target could go, which is the first occurrence when it exists. C++'s std::lower_bound and Python's bisect_left do this.
Can I search strings?
This visualizer uses numbers. The same method works on any sorted data.
Is the binary search visualizer free to use?
Yes, the binary search visualizer is free and costs nothing. Running your first search shows a short form for your name and WhatsApp number one time; once that's done, this tool and every other Uncodemy tool open with no form.