Skip to content

Instantly share code, notes, and snippets.

@mariusschulz
Created March 8, 2014 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mariusschulz/9431926 to your computer and use it in GitHub Desktop.
Save mariusschulz/9431926 to your computer and use it in GitHub Desktop.
private static bool BinarySearch(int[] sortedHaystack, int needle)
{
int leftBoundary = 0;
int rightBoundary = sortedHaystack.Length - 1;
while (leftBoundary <= rightBoundary)
{
int pivotIndex = (int)(((long)leftBoundary + rightBoundary) / 2);
int pivotValue = sortedHaystack[pivotIndex];
if (pivotValue == needle)
return true;
if (leftBoundary == rightBoundary)
break;
if (needle < pivotValue)
rightBoundary = pivotIndex;
else
leftBoundary = pivotIndex + 1;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment