Last active
February 9, 2019 23:25
-
-
Save FrankKerrigan/751865fa0242ba1e9ec72b4cda51333d to your computer and use it in GitHub Desktop.
C# Binary Search Recursive call
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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