Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Last active June 21, 2021 04:21
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/ee67e5c9da66740cf8c6d1a29e82f7b1 to your computer and use it in GitHub Desktop.
Save parzibyte/ee67e5c9da66740cf8c6d1a29e82f7b1 to your computer and use it in GitHub Desktop.
static void Main(string[] args)
{
int[] numeros = { 999, 28, 11, 96, 1, 2, 45, 0, 1 };
// Primero lo ordenamos. Puede ser con cualquier método, yo usaré un comparador
// https://parzibyte.me/blog/2019/04/04/ordenar-arreglos-cadena-numericos-c-sharp/
Array.Sort<int>(numeros, new Comparison<int>((n1, n2) => n1.CompareTo(n2)));
// Imprimirlo ordenado
Console.WriteLine("El arreglo es:");
foreach (var numero in numeros)
{
Console.Write(numero + ",");
}
Console.WriteLine("");
// Ahora sí, buscar de manera binaria
int busqueda = 11;
int indice = busquedaBinaria(numeros, busqueda, 0, numeros.Length - 1);
// Con while sería:
// int indice = busquedaBinariaWhile(numeros, busqueda);
if (indice == -1)
{
Console.WriteLine("La búsqueda no existe");
}
else
{
Console.WriteLine("El elemento {0} existe en la posición {1}", busqueda, indice);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment