Skip to content

Instantly share code, notes, and snippets.

@FrankKerrigan
Last active February 9, 2019 23:26
Show Gist options
  • Save FrankKerrigan/be707616e93bcd59dddef32e37d6b039 to your computer and use it in GitHub Desktop.
Save FrankKerrigan/be707616e93bcd59dddef32e37d6b039 to your computer and use it in GitHub Desktop.
C# Binary Search non-recursive
static void BinarySearch()
{
// sort array
var list = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 23, 44, 66, 77, 88, 99, 101, 102, 104, 170, 344, 445, 565, 673, 733, 874, 912, 1001, 1120 };
var searchTerm = 9999;
int result = -1; //assume is all postive numbers
var start = 0;
var end = list.Length;
int RecordPosition = -1;
while (searchTerm != result)
{
int mid = ((end - start) / 2) + start;
result = list[mid];
RecordPosition = mid; // will be last one tested;
start = (searchTerm < result) ? start : start + ((end - start) / 2);
end = (searchTerm < result) ? end - ((end - start) / 2) : end;
if (searchTerm != result && Math.Abs(start - end) == 1 && mid != 1)
{
result = -1;
Consle.WriteLine($"Seatch Term: {searchTerm} NOT Found!");
return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment