查找给定值
int binaryFind(int *arr,int len,int val) {
int left = 0; int right = len-1;
while (left <= right) {
int mid = left + (right - left)/2;
if (arr[mid] < val) {
left = mid + 1;
} else if (arr[mid] > val) {
right = mid - 1;
} else {
return mid;
}
}
return -1;
}
int binaryFind(int *arr,int len,int val) {
int left = 0; int right = len;
while (left < right) {
int mid = left + (right - left)/2;
if (arr[mid] < val) {
left = mid + 1;
} else if (arr[mid] > val) {
right = mid;
} else {
return mid;
}
}
return -1;
}
查找大于给定值的第一个元素
- 被用于二分插入排序
- left:大于给定值的第一个元素的下标
- right = left - 1:小于等于给定值的最后一个元素下标
int binaryFind(int *arr,int len,int val) {
int left = 0; int right = len-1;
while (left <= right) {
int mid = left + (right - left)/2;
if (arr[mid] <= val) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
查找小于给定值的最后一个元素
- left = right + 1:大于等于给定值的第一个元素的下标
- right:小于给定值的最后一个元素下标
int binaryFind(int *arr,int len,int val) {
int left = 0; int right = len-1;
while (left <= right) {
int mid = left + (right - left)/2;
if (arr[mid] < val) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return right;
}