Skip to content

Instantly share code, notes, and snippets.

@takint
Last active July 2, 2019 18:43
Show Gist options
  • Save takint/fc0855167b1ad8f5ed5fc1fcf8f2891c to your computer and use it in GitHub Desktop.
Save takint/fc0855167b1ad8f5ed5fc1fcf8f2891c to your computer and use it in GitHub Desktop.
// Iterative
static int BinarySearch(int[] arr, int value)
{
int left = 0;
int right = arr.Length - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (arr[mid] == value)
{
return mid;
}
else if (value > arr[mid])
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return -1;
}
// Recursive
static int BinarySearch(int[] arr, int left, int right, int value)
{
if (left <= right)
{
int mid = left + (right - left) / 2;
if (arr[mid] == value)
{
return mid;
}
else if (value > arr[mid])
{
return BinarySearch(arr, mid + 1, right, value);
}
else
{
return BinarySearch(arr, left, mid - 1, value);
}
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment