int search(int arr[],int left, int right, int key)
{
if(!arr) return -1;
while(left <= right)
{
int mid = left + right >> 1;
if(arr[mid] == key) return mid;
else if(arr[mid] < key) left = mid + 1;
else right = mid - 1;
}
return -1;
}
int findFirstEqual(int arr[],int length, int key)
{
if(!arr) return -1;
int left = 0, right = length - 1;
while(left <= right)
{
int mid = left + right >> 1;
if(arr[mid] >= key) right = mid - 1;
else left = mid + 1;
}
if(left < length && arr[left] ==key) return left;
return -1;
}
int findLastEqual(int arr[],int length, int key)
{
if(!arr) return -1;
int left = 0, right = length - 1;
while(left <= right)
{
int mid = left + right >> 1;
if(arr[mid] > key) right = mid - 1;
else left = mid + 1;
}
if(right >= 0 && arr[right] ==key) return right;
return -1;
}
int findLastEqualSmaller(int array[], int length, int key) {
int left = 0;
int right = length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (array[mid] > key) {
right = mid - 1;
}
else {
left = mid + 1;
}
}
return right;
}
int findFirstEqualLarger(int array[], int length, int key) {
int left = 0;
int right = length - 1;
while (left <= right)
{
int mid = left + right >> 1;
if (array[mid] >= key) right = mid - 1;
else left = mid + 1;
}
return left;
}
来个总结:
int findFirstEqual(int[] arr, int length, int key)
{
int l = 0, r = length - 1;
while (l <= r)
{
var mid = (l + r) >> 1;
if (arr[mid] >= key) r = mid - 1;
else l = mid + 1;
}
if (l < length && arr[l] == key) return l;
return -1;
}
int findLastEqual(int[] arr, int length, int key)
{
int l = 0, r = length - 1;
while (l <= r)
{
var mid = (l + r) >> 1;
if (arr[mid] <= key) l = mid + 1;
else r = mid - 1;
}
if (r < length && arr[r] == key) return r;
return -1;
}