intsearchFirstEqual(int *arr, int n, int key) { int left = 0, right = n-1; while(left<=right) { int mid = (left+right)/2; if(arr[mid] >= key) right = mid - 1; elseif(arr[mid] < key) left = mid + 1; } if( left < n && arr[left] == key) return left; return-1; }
找出最后一个与key相等的元素
1 2 3 4 5 6 7 8 9 10 11
intsearchLastEqual(int *arr, int n, int key) { int left = 0, right = n-1; while(left<=right) { int mid = (left+right)/2; if(arr[mid] > key) right = mid - 1; elseif(arr[mid] <= key) left = mid + 1; } if( right>=0 && arr[right] == key) return right; return-1; }
查找第一个等于或者大于Key的元素
1 2 3 4 5 6 7 8 9 10
intsearchFirstEqualOrLarger(int *arr, int n, int key) { int left=0, right=n-1; while(left<=right) { int mid = (left+right)/2; if(arr[mid] >= key) right = mid-1; elseif (arr[mid] < key) left = mid+1; } return left; }
查找第一个大于key的元素
1 2 3 4 5 6 7 8 9 10
intsearchFirstLarger(int *arr, int n, int key) { int left=0, right=n-1; while(left<=right) { int mid = (left+right)/2; if(arr[mid] > key) right = mid-1; elseif (arr[mid] <= key) left = mid+1; } return left; }
查找最后一个等于或者小于key的元素
1 2 3 4 5 6 7 8 9 10
int searchLastEqualOrSmaller(int *arr, int n, int key) { int left=0, right=n-1; while(left<=right) { int m = (left+right)/2; if(arr[m] > key) right = m-1; else if (arr[m] <= key) left = m+1; } return right; }
查找最后一个小于key的元素
1 2 3 4 5 6 7 8 9 10
intsearchLastSmaller(int *arr, int n, int key) { int left=0, right=n-1; while(left<=right) { int mid = (left+right)/2; if(arr[mid] >= key) right = mid-1; elseif (arr[mid] < key) left = mid+1; } return right; }