binary-search.js
function binarySearch(a, target) {
let lo = 0;
let hi = a.length - 1;
while (lo <= hi) {
let mid = Math.floor((lo + hi) / 2);
if (a[mid] === target) return mid;
if (a[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
binarySearch([1, 3, 5, 7, 9, 11], 9);
What to watch
The lo / mid / hi pointers jump across the array as the range collapses by half.
Reading binary searchon a page only gets you so far - code is a process, and the process happens at runtime where you can't normally see it. In NeonFlow, this exact program runs step by step: every call opens a frame, every branch picks a path, and every value moves through memory in front of you. That's the fastest way to actually understand how binary search works.
Run binary search yourself
Open NeonFlow, paste this code (or any of your own), and scrub through it one step at a time.
Open NeonFlow