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

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more