Skip to content

Instantly share code, notes, and snippets.

@MrDave1999
Created July 27, 2019 03:54
Show Gist options
  • Save MrDave1999/843654eb567b730bd9af8755ec1a6fa0 to your computer and use it in GitHub Desktop.
Save MrDave1999/843654eb567b730bd9af8755ec1a6fa0 to your computer and use it in GitHub Desktop.
Implementación de un método para hacer búsqueda binaria en C#.
using System;
class Program
{
static void Main()
{
int data1;
double data2;
int []arrInt = new int[10]{0, 5, 10, 15, 20, 25, 30, 35, 40, 45};
double []arrFloat = new double[10]{0, 5.5, 10.5, 15.4, 20.5, 25.5, 30.67, 35.98, 40.32, 45.90};
Console.Write("Ingrese un valor:\n");
data1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("El numero {0} {1} se encuentra en el arreglo.\n\n", data1, (SearchBinary.BBIterative<int>(arrInt, data1) == -1) ? ("no") : ("si"));
Console.Write("Ingrese un valor:\n");
data2 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("El numero {0} {1} se encuentra en el arreglo.\n\n", data2, (SearchBinary.BBIterative<double>(arrFloat, data2) == -1) ? ("no") : ("si"));
Console.ReadLine();
}
}
using System;
class SearchBinary
{
public static int BBIterative<T>(T []pv, T data) where T : IComparable<T>
{
int first = 0;
int end = pv.Length - 1;
int medium;
int i = 0;
while(first <= end)
{
++i;
medium = (first + end) / 2;
if(pv[medium].CompareTo(data) == 0) //pv[medium] == data
{
Console.WriteLine("Iteraciones: {0}\n", i);
return medium;
}
if(data.CompareTo(pv[medium]) > 0) //data > pv[medium]
first = medium + 1;
else
end = medium - 1;
}
Console.WriteLine("Iteraciones: {0}\n", i);
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment