Created
January 13, 2022 15:19
-
-
Save kmb385/9233cf2d35739a80ecf30317d047c5a6 to your computer and use it in GitHub Desktop.
C# Binary Search
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
int[] nums = { 33, 44, 55, 66, 77, 88, 99, 100 }; | |
int index = BinarySearch(nums, 99); | |
Console.WriteLine(index); | |
int BinarySearch(int[] nums, int target) | |
{ | |
int low = 0, high = nums.Length - 1; | |
while (low <= high) | |
{ | |
int midpoint = (low + high) / 2; | |
if (nums[midpoint] == target) | |
{ | |
return midpoint; | |
} | |
if (target < nums[midpoint]) | |
{ | |
high = midpoint - 1; | |
} | |
else | |
{ | |
low = midpoint + 1; | |
} | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment