Created
August 6, 2019 05:49
-
-
Save parzibyte/21ae3746a0993031cef0d3da7c23ee81 to your computer and use it in GitHub Desktop.
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 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