Skip to content

Instantly share code, notes, and snippets.

@aannenko
Created May 30, 2024 14:20
Show Gist options
  • Save aannenko/2a46706dc80150548761cfb7fba797a1 to your computer and use it in GitHub Desktop.
Save aannenko/2a46706dc80150548761cfb7fba797a1 to your computer and use it in GitHub Desktop.
Binary search, iterative and recursive
var ints = new int[] { 2, 3, 4, 10, 40 };
Console.WriteLine(IndexOfUsingIterativeBinarySearch(ints, 3)); // 1
Console.WriteLine(IndexOfUsingRecursiveBinarySearch(ints, 0, ints.Length - 1, 3)); // 1
static int IndexOfUsingIterativeBinarySearch(int[] ints, int searchedValue)
{
int low = 0;
int high = ints.Length - 1;
while (low <= high)
{
int mid = low + (high - low) / 2;
if (ints[mid] == searchedValue)
return mid;
if (ints[mid] < searchedValue)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
static int IndexOfUsingRecursiveBinarySearch(int[] ints, int low, int high, int searchedValue)
{
if (low <= high)
{
int mid = low + (high - low) / 2;
if (ints[mid] == searchedValue)
return mid;
return ints[mid] > searchedValue
? IndexOfUsingRecursiveBinarySearch(ints, low, mid - 1, searchedValue)
: IndexOfUsingRecursiveBinarySearch(ints, mid + 1, high, searchedValue);
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment