Created
March 2, 2014 03:43
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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