Skip to content

Instantly share code, notes, and snippets.

@lupomontero
Created March 26, 2017 06:26
Show Gist options
  • Save lupomontero/9fe405d30cbcc36f57015a0d2a6d6729 to your computer and use it in GitHub Desktop.
Save lupomontero/9fe405d30cbcc36f57015a0d2a6d6729 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) {
var min = 0;
var max = array.length - 1;
while (min <= max) {
var middle = Math.floor((min + max) / 2);
var guess = array[middle];
if (guess === item) {
return middle;
}
if (guess > item) {
max = middle - 1;
}
else {
min = middle + 1;
}
}
return -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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment