Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Last active June 21, 2021 04:23
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/5044362c3f8c9d7d862b7fe2e5574aa9 to your computer and use it in GitHub Desktop.
Save parzibyte/5044362c3f8c9d7d862b7fe2e5574aa9 to your computer and use it in GitHub Desktop.
static int busquedaBinaria(int[] arreglo, int busqueda, int izquierda, int derecha)
{
if (izquierda > derecha)
{
return -1;
}
// Comprobar si está en el centro
int indiceCentral = Convert.ToInt32(Math.Floor(Convert.ToDouble(izquierda + derecha) / 2));
int valorCentral = arreglo[indiceCentral];
if (valorCentral == busqueda)
{
return indiceCentral;
}
// Si no, debido a que esto ya está ordenado, analizamos dónde podría estar
if (busqueda < valorCentral)
{
// Si lo que buscamos es menor, debe estar a la izquierda
derecha = indiceCentral - 1;
}
else
{
// Si no, está a la derecha
izquierda = indiceCentral + 1;
}
return busquedaBinaria(arreglo, busqueda, izquierda, derecha);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment