Skip to content

Instantly share code, notes, and snippets.

@kmb385
Created January 13, 2022 15:19
Show Gist options
  • Save kmb385/9233cf2d35739a80ecf30317d047c5a6 to your computer and use it in GitHub Desktop.
Save kmb385/9233cf2d35739a80ecf30317d047c5a6 to your computer and use it in GitHub Desktop.
C# Binary Search
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