← All lessons
How binary search works
Halve the array until one cell is left
binary-search.js
function binarySearch(arr, target) { let lo = 0; let hi = arr.length - 1; while (lo <= hi) { // JS numbers can't overflow here; in C or Java write lo + (hi - lo) / 2 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; // lo passed hi: nothing left to check}Grow the array and count the compares
linear-search.js
function linearSearch(arr, target) { // reads every cell until it hits for (let i = 0; i < arr.length; i++) { if (arr[i] === target) return i; } return -1;}binary-search.js
function binarySearch(arr, target) { let lo = 0; let hi = arr.length - 1; while (lo <= hi) { // JS numbers can't overflow here; in C or Java write lo + (hi - lo) / 2 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; // lo passed hi: nothing left to check}Break it with unsorted data same numbers, different order
Probes
Actually in the array
Sorting costs O(n log n) once, so it pays off when you search the same data many times
binary-search.js
while (lo <= hi) { const mid = Math.floor((lo + hi) / 2); if (arr[mid] === target) return mid; // only safe because the array is sorted if (arr[mid] < target) lo = mid + 1; else hi = mid - 1;}return -1;Topics
Next: How Big O notation works
Open lesson