Skip to content

Instantly share code, notes, and snippets.

@erosenberg
Last active October 1, 2017 15:52
Show Gist options
  • Save erosenberg/c7a7ace930575b66b3d1ef6b14945e39 to your computer and use it in GitHub Desktop.
Save erosenberg/c7a7ace930575b66b3d1ef6b14945e39 to your computer and use it in GitHub Desktop.
Binary Search with Recursion
let moves = 0;
const findItem = (arr, target) => {
if (!Array.isArray(arr)) return arr;
moves++;
const midIndex = Math.floor(arr.length / 2);
const midValue = arr[midIndex];
if (target === midValue) {
return midValue;
} else if (midValue > target) {
const leftHalf = arr.slice(0, midIndex);
return findItem(leftHalf, target);
} else if (midValue < target) {
const rightHalf = arr.slice((midIndex + 1), arr.length);
return findItem(rightHalf, target);
}
};
const input = [1, 2, 3, 4, 5, 6, 19, 20, 100, 115, 190];
const myIndex = findItem(input, 115);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment