Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created August 7, 2019 16:04
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/76cddd32a536d2479e32570a58448ea8 to your computer and use it in GitHub Desktop.
Save parzibyte/76cddd32a536d2479e32570a58448ea8 to your computer and use it in GitHub Desktop.
/**
*
* Implementación del algoritmo de
* búsqueda binaria recursiva en un arreglo usando C
*
* Funciona con arreglos de números
*
* Autor: parzibyte
* Web: parzibyte.me/blog
*/
int busquedaBinariaConWhile(int arreglo[], int busqueda, int tamanioDelArreglo){
// Nota: el tamaño del arreglo es necesario porque cuando se recibe
// como argumento no se puede calcular dentro de la función
int izquierda = 0, derecha = tamanioDelArreglo - 1;
while (izquierda <= derecha){
int indiceDeLaMitad = floor((izquierda + derecha) / 2);
int valorQueEstaEnElMedio = arreglo[indiceDeLaMitad];
if (busqueda == valorQueEstaEnElMedio){
// En caso de encontrar lo que buscamos, terminamos la función
// y regresamos el índice
return indiceDeLaMitad;
}
if (busqueda < valorQueEstaEnElMedio){
// Entonces está hacia la izquierda
derecha = indiceDeLaMitad - 1;
}else{
// Está hacia la derecha
izquierda = indiceDeLaMitad + 1;
}
}
// Termina el ciclo y no encontramos nada
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment