Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created August 6, 2019 05:49
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/21ae3746a0993031cef0d3da7c23ee81 to your computer and use it in GitHub Desktop.
Save parzibyte/21ae3746a0993031cef0d3da7c23ee81 to your computer and use it in GitHub Desktop.
/**
*
* Implementación del algoritmo de
* búsqueda binaria con while en un arreglo usando C
*
* Funciona con arreglos de cadenas
*
* Autor: parzibyte
* Web: parzibyte.me/blog
*/
int busquedaBinariaWhile(char arreglo[][MAXIMA_LONGITUD_CADENA], char busqueda[], int longitudDelArreglo){
int izquierda = 0, derecha = longitudDelArreglo - 1;
while(izquierda <= derecha){
int indiceDeLaMitad = floor((izquierda + derecha) / 2);
char *elementoDeLaMitad = arreglo[indiceDeLaMitad];
int resultadoDeLaComparacion = strcmp(busqueda, elementoDeLaMitad);
// Si son iguales hemos encontrado el elemento
if (resultadoDeLaComparacion == 0) return indiceDeLaMitad;
// Si no, vemos en cuál mitad podría estar
// ¿A la izquierda?
if (resultadoDeLaComparacion < 0){
derecha = indiceDeLaMitad - 1;
}else{
// A la derecha
izquierda = indiceDeLaMitad + 1;
}
}
// Si termina el ciclo y no encontramos nada, regresamos -1
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment