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/1c0e34eff0df1fd7f6f2ac809e86e8ce to your computer and use it in GitHub Desktop.
Save parzibyte/1c0e34eff0df1fd7f6f2ac809e86e8ce 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 cadenas
*
* Autor: parzibyte
* Web: parzibyte.me/blog
*/
int busquedaBinariaRecursiva(char arreglo[][MAXIMA_LONGITUD_CADENA], char busqueda[], int izquierda, int derecha){
if (izquierda > derecha) return -1;
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;
}
// Recursión justo aquí
return busquedaBinariaRecursiva(arreglo, busqueda, izquierda, derecha);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment