Published
Edited
Dec 15, 2021
1 star
Insert cell
# Binary Search
Insert cell
Insert cell
{
const array = [1, 1, 5, 124, 400, 1004, 2897, 9878];

function binarySearch(array, val, left = 0, right = array.length - 1) {
let mid = Math.floor((left + right) / 2);

if (left > right) return -1;
if (val === array[mid]) return mid;
else if (val < array[mid]) return binarySearch(array, val, left, mid - 1);
else return binarySearch(array, val, mid + 1, right);
}

return binarySearch(array, 2897);
}
Insert cell
Insert cell
Insert cell
class BinarySearchTree {
constructor() {
this.root = null;
}

insert(value, node = this.root) {
if (!this.root) {
this.root = new Node(value);
return;
}

if (value <= node.value) {
if (!node.left) node.left = new Node(value);
else this.insert(value, node.left);
} else {
if (!node.right) node.right = new Node(value);
else this.insert(value, node.right);
}
}

search(value, node = this.root) {
if(value === node.value) return node;

if(value <= node.value) {
return this.search(value, node.left);
} else {
return this.search(value, node.right);
}
}
}
Insert cell
{
const tree = new BinarySearchTree();

for (const val of [10, 6, 7, 5, 3, 2, 1, 4, 8, 9, 12, 40]) {
tree.insert(val);
}

console.log(tree.search(8));
console.log(tree.search(12));
console.log(tree.search(4));

return tree;
}
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