Last active
February 9, 2019 23:26
-
-
Save FrankKerrigan/be707616e93bcd59dddef32e37d6b039 to your computer and use it in GitHub Desktop.
C# Binary Search non-recursive
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 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