Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save servatj/f0826ba27086fa60f7d8b405a950f0fd to your computer and use it in GitHub Desktop.
Save servatj/f0826ba27086fa60f7d8b405a950f0fd to your computer and use it in GitHub Desktop.
/*
Búsqueda binaria (Binary Search): Implementación de ejemplo.
Recibe un array ordenado y el elemento a buscar. Si encuentra el elemento
devolverá el índice del elemento encontrado, si no se encuentra devolverá `-1`.
*/
function binarySearch(array, item) {
function recurse(min, max) {
if (min > max) {
return -1;
}
var middle = Math.floor((min + max) / 2);
if (array[middle] === item) {
return middle;
}
if (array[middle] > item) {
return recurse(min, middle - 1);
}
return recurse(middle + 1, max);
}
return recurse(0, array.length - 1);
}
console.log(binarySearch([1, 2, 3, 4, 6, 8, 9], 8)); // 5
console.log(binarySearch([1, 2, 3, 4, 6, 8, 9], 7)); // -1
console.log(binarySearch([1, 2, 3, 4, 6, 8, 9], 9)); // 6
console.log(binarySearch([1], 0)); // -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment