Created
March 20, 2017 19:42
-
-
Save hdorothea/b6791e0cee2e3898b7e8c0c2da6631e3 to your computer and use it in GitHub Desktop.
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
// input is an ordered array | |
let input_1 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] | |
// we pick a random value from the input array | |
let randomValue = input_1[Math.floor(Math.random() * input_1.length)]; | |
let binaryGuessIndex = (sortedArray:any[]): number => Math.floor(sortedArray.length/2) | |
function search (sortedArray:any[], value:any): any { | |
let guessIndex = binaryGuessIndex(sortedArray); | |
let guess = sortedArray[guessIndex] | |
if (value < guess) { | |
guess = search(sortedArray.slice(0,guessIndex), value); | |
return guess; | |
} | |
if (value > guess) { | |
guess = search(sortedArray.slice(guessIndex+1, sortedArray.length), value); | |
return guess | |
} | |
if (value == guess) { | |
return guess; | |
} | |
} | |
console.log(search(input_1, randomValue)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment