Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created August 7, 2019 16:44
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 parzibyte/4caaadc6b0deac44a8f2287c4721d6df to your computer and use it in GitHub Desktop.
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/
/**
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