Skip to content

Instantly share code, notes, and snippets.

@begeekmyfriend
Created March 2, 2014 03:43
Show Gist options
  • Save begeekmyfriend/9301579 to your computer and use it in GitHub Desktop.
Save begeekmyfriend/9301579 to your computer and use it in GitHub Desktop.
Only less than 10% programmers all over the world can get it right.
int binary_search_first_position(int *A, int n, int target)
{
int low = -1, high = n;
assert(A != NULL && n >= 0);
while (low + 1 < high)
{
int mid = (low + high) >> 1;
if (A[mid] < target)
low = mid;
else
high = mid;
}
if (high >= n || A[high] != target)
return -high - 1;
else
return high; // high == low + 1
}
int binary_search_last_position(int *A, int n, int target)
{
int low = -1, high = n;
assert(A != NULL && n >= 0);
while (low + 1 < high)
{
int mid = (low + high) >> 1;
if (A[mid] > target)
high = mid;
else
low = mid;
}
if (low < 0 || A[low] != target)
return -low - 2;
else
return low; // low == high - 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment