Created
January 10, 2020 23:52
-
-
Save amejiarosario/5c278da7a2e7053301d699f1e643aa6c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function indexOf(array, element, offset = 0) { | |
// split array in half | |
const half = parseInt(array.length / 2); | |
const current = array[half]; | |
if(current === element) { | |
return offset + half; | |
} else if(element > current) { | |
const right = array.slice(half); | |
return indexOf(right, element, offset + half); | |
} else { | |
const left = array.slice(0, half) | |
return indexOf(left, element, offset); | |
} | |
} | |
// Usage example with a list of names in ascending order: | |
const directory = ["Adrian", "Bella", "Charlotte", "Daniel", "Emma", "Hanna", "Isabella", "Jayden", "Kaylee", "Luke", "Mia", "Nora", "Olivia", "Paisley", "Riley", "Thomas", "Wyatt", "Xander", "Zoe"]; | |
console.log(indexOf(directory, 'Hanna')); // => 5 | |
console.log(indexOf(directory, 'Adrian')); // => 0 | |
console.log(indexOf(directory, 'Zoe')); // => 18 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment