Published
Edited
Jun 8, 2022
Insert cell
# Binary search
Insert cell
function binarySearch(arr, target) {
let [left, right, mid] = [0, arr.length - 1, 0];

while (left <= right) {
mid = Math.floor((left + right) / 2);

if (arr[mid] === target) return mid;
if (target < arr[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
}

return false;
}
Insert cell
binarySearch([1, 3, 5, 7, 9], 9)
Insert cell
binarySearch([1, 3, 5, 7, 9], 7)
Insert cell
binarySearch([1, 3, 5, 7, 9], 5)
Insert cell
binarySearch([1, 3, 5, 7, 9], 3)
Insert cell
binarySearch([1, 3, 5, 7, 9], 1)
Insert cell
binarySearch([1, 3, 5, 7, 9], 0)
Insert cell
function recursiveBinarySearch(arr, target, left = 0, right = arr.length - 1) {
if (left > right) return false;
let mid = Math.floor((left + right) / 2);

if (arr[mid] === target) return mid;
if (target < arr[mid]) {
return recursiveBinarySearch(arr, target, left, mid - 1);
} else {
return recursiveBinarySearch(arr, target, mid + 1, right);
}
}
Insert cell
recursiveBinarySearch([1, 3, 5, 7, 9], 4)
Insert cell
recursiveBinarySearch([1, 3, 5, 7, 9], 5)
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more