@MrXiao
2018-03-08T16:39:40.000000Z
字数 2639
阅读 814
算法
二分查找法是对一组有序的数字中进行查找,传递相应的数据,进行比较查找到与原数据相同的数据,查找到了返回对应的数组下标,没有找到返回-1;
while循环
/**
* 循环实现
* @param array 已排序数组
* @param target 目标
* @return 找不到返回-1,找到返回下标
*/
private static int binarySearch(int[] array, int target) {
int low = 0;
int high = array.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2; //注意此处写法,避免越界
if (array[mid] > target) {
high = mid - 1;
} else if (array[mid] < target) {
low = mid + 1;
} else {
return mid;
}
}
return -1;
}
递归实现
private static int binarySearch(int[] array, int target, int low, int high) {
int mid = low + (high - low) / 2;
if (array[mid] == target) {
return mid;
}
if (low >= high) {
return -1;
} else if (target > array[mid]) {
return binarySearch(array, target, mid + 1, high);
} else if (target < array[mid]) {
return binarySearch(array, target, low, mid - 1);
}
return -1;
}
随着二分查找的进行,如果找到key并不结束循环的话,最终的结束状态会是right < left,并且right + 1 = left。
那么,可以找到:
另外,如果存在多个key时,稍加判断,就可以找到
while (left <= right) {
mid = (left + right) / 2;
if (key ? arr[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return ?;
根据要求的值的位置,先确定比较符号,再确定返回值,
比较符号:左<=,右<
返回值:左right,右left
//1 查找最后一个小于key的元素
int findLastLess(int arr[], int len, int key) {
int left = 0;
int right = len - 1;
int mid;
while (left <= right) {
mid = left + (right - left) / 2;
if (key <= arr[mid]) { // <= 意为左
right = mid - 1;
} else {
left = mid + 1;
}
}
return right; //返回左边值right
}
//2 查找第一个大于等于key的元素
int findLastLess(int arr[], int len, int key) {
int left = 0;
int right = len - 1;
int mid;
while (left <= right) {
mid = left + (right - left) / 2;
if (key <= arr[mid]) { // <= 意为左
right = mid - 1;
} else {
left = mid + 1;
}
}
return left; //返回右边值left
}
//3 查找第一个大于等于key的元素
int findLastLess(int arr[], int len, int key) {
int left = 0;
int right = len - 1;
int mid;
while (left <= right) {
mid = left + (right - left) / 2;
if (key < arr[mid]) { // <= 意为右
right = mid - 1;
} else {
left = mid + 1;
}
}
return right; //返回左边值right
}
//4 查找第一个大于key的元素
int findLastLess(int arr[], int len, int key) {
int left = 0;
int right = len - 1;
int mid;
while (left <= right) {
mid = left + (right - left) / 2;
if (key < arr[mid]) { // <= 意为右
right = mid - 1;
} else {
left = mid + 1;
}
}
return left; //返回右边值left
}
//5 查找第一个与key相等的元素
int findFirstEqual(int arr[], int len, int key) {
int left = 0;
int right = len - 1;
int mid;
while (left <= right) {
mid = left + (right - left) / 2;
if (key <= arr[mid]) { // <= 意为左
right = mid - 1;
} else {
left = mid + 1;
}
}
//right是最后一个小于key的
//left是第一个大于等于key的
if (left < len && arr[left] == key) {
return left;
}
return -1;
}
//6 查找最后一个与key相等的元素
int findLastEqual(int arr[], int len, int key) {
int left = 0;
int right = len - 1;
int mid;
while (left <= right) {
mid = left + (right - left) / 2;
if (key < arr[mid]) { // < 意为右
right = mid - 1;
} else {
left = mid + 1;
}
}
//right是最后一个小于key的
//left是第一个大于等于key的
if (right >= 0 && arr[right] == key) {
return right;
}
return -1;
}