Created
August 7, 2019 16:44
-
-
Save parzibyte/4caaadc6b0deac44a8f2287c4721d6df to your computer and use it in GitHub Desktop.
Búsqueda binaria secuencial en arreglos de enteros y Java - https://parzibyte.me/blog/2018/10/31/busqueda-binaria-arreglos-java/
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
/** | |
Algoritmo de búsqueda binaria secuencial en Java | |
@author parzibyte | |
@web parzibyte.me/blog | |
*/ | |
public static int busquedaBinariaConWhile(int[] arreglo, int busqueda){ | |
int izquierda = 0, derecha = arreglo.length - 1; | |
while(izquierda <= derecha){ | |
// Calculamos las mitades... | |
int indiceDelElementoDelMedio = (int) Math.floor((izquierda + derecha) / 2); | |
int elementoDelMedio = arreglo[indiceDelElementoDelMedio]; | |
// Ver si está en la mitad y romper aquí el ciclo | |
if(elementoDelMedio == busqueda){ | |
return indiceDelElementoDelMedio; | |
} | |
// Si no, entonces vemos si está a la izquierda o derecha | |
if(busqueda < elementoDelMedio){ | |
derecha = indiceDelElementoDelMedio - 1; | |
}else{ | |
izquierda = indiceDelElementoDelMedio + 1; | |
} | |
} | |
// Si no se rompió el ciclo ni se regresó el índice, entonces el elemento no existe | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment