Skip to content

Instantly share code, notes, and snippets.

@kpol
Last active September 15, 2020 02:19
Show Gist options
  • Select an option

  • Save kpol/861b8f946a65a2c5833b728c6365cb8a to your computer and use it in GitHub Desktop.

Select an option

Save kpol/861b8f946a65a2c5833b728c6365cb8a to your computer and use it in GitHub Desktop.
public static int BinarySearch(int[] arr, int k)
{
var minIndex = 0;
var maxIndex = arr.Length - 1;
while (minIndex <= maxIndex)
{
var mid = (minIndex + maxIndex) / 2;
if (k == arr[mid])
{
return mid;
}
if (k < arr[mid])
{
maxIndex = mid - 1;
}
else
{
minIndex = mid + 1;
}
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment