Created
August 6, 2019 05:49
-
-
Save parzibyte/1c0e34eff0df1fd7f6f2ac809e86e8ce to your computer and use it in GitHub Desktop.
Búsqueda binaria recursiva en C - https://parzibyte.me/blog/2018/11/08/busqueda-binaria-arreglos-cadenas-c/
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
/** | |
* | |
* 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