Created
March 26, 2017 08:04
-
-
Save lupomontero/9de42333f07b7ae142765b96b626d8ce 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
/* | |
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