Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created June 21, 2021 04:18
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/ec25a9e46a3dc79e908b9ea5106bc4ff to your computer and use it in GitHub Desktop.
Save parzibyte/ec25a9e46a3dc79e908b9ea5106bc4ff to your computer and use it in GitHub Desktop.
static int busquedaBinariaWhile(int[] arreglo, int busqueda)
{
int izquierda = 0, derecha = arreglo.Length - 1;
while (izquierda <= derecha)
{
int indiceCentral = Convert.ToInt32(Math.Floor(Convert.ToDouble(izquierda + derecha) / 2));
int valorCentral = arreglo[indiceCentral];
// Si lo encontramos entonces regresamos el valor de manera inmediata
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;
}
}
// Terminamos de buscar y no encontramos el elemento
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment