Skip to content

Instantly share code, notes, and snippets.

@amejiarosario
Created January 10, 2020 23:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amejiarosario/5c278da7a2e7053301d699f1e643aa6c to your computer and use it in GitHub Desktop.
Save amejiarosario/5c278da7a2e7053301d699f1e643aa6c to your computer and use it in GitHub Desktop.
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