Skip to content

Instantly share code, notes, and snippets.

@FrankKerrigan
Last active February 9, 2019 23:25
Show Gist options
  • Save FrankKerrigan/751865fa0242ba1e9ec72b4cda51333d to your computer and use it in GitHub Desktop.
Save FrankKerrigan/751865fa0242ba1e9ec72b4cda51333d to your computer and use it in GitHub Desktop.
C# Binary Search Recursive call
static void GetBinarySearchRecursive()
{
var list = new[] { 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 };
int searchTerm = 102;
int start = 0;
int end = list.Length;
var RecordNo = BinarySearchRecursive(ref list, start, end, searchTerm);
if (RecordNo == -1)
{
Console.WriteLine("Record not found");
return;
}
Console.WriteLine($"Seatch Term: {searchTerm} Record Position: {RecordNo}, Value: {list[RecordNo]}");
}
static int BinarySearchRecursive(ref int[] terms, int start, int end, int searchterm)
{
int mid = ((end - start) / 2) + start;
int result = terms[mid];
if (result == searchterm)
return mid;
start = (searchterm < result) ? start : start + ((end - start) / 2);
end = (searchterm < result) ? end - ((end - start) / 2) : end;
if (Math.Abs(start - end) == 1 && mid != 1)
return -1;
return BinarySearchRecursive(ref terms, start, end, searchterm);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment