Last active
October 1, 2017 15:52
-
-
Save erosenberg/c7a7ace930575b66b3d1ef6b14945e39 to your computer and use it in GitHub Desktop.
Binary Search with Recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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