Skip to content

Instantly share code, notes, and snippets.

@DCCoder90
Created September 30, 2019 15:00
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 DCCoder90/07a1975e8aec76b3a4b721885d050496 to your computer and use it in GitHub Desktop.
Save DCCoder90/07a1975e8aec76b3a4b721885d050496 to your computer and use it in GitHub Desktop.
Quick and dirty example of a binary search (using LinqPad)
void Main()
{
int[] intArray = new int[]{ 51,83,2523,2452,124,656,254,115,15,5,5,15,156,4378,568,4,37,2,72,2,8,9,10,234,39,23,56,1,63,33};
var list = intArray.ToList();
list.Sort();
var find = search(list,656);
find.Dump();
}
public bool search(IEnumerable<int> array, int value){
var contents = array.ToList();
var length = contents.Count()/2;
var midway = contents.ElementAt(length);
contents.Dump("Contents");
midway.Dump("Midway Point");
if(midway > value)
return search(contents.Take(length),value);
if(midway < value)
return search(contents.Skip(length),value);
if(midway == value)
return true;
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment