原作者:老铁123
出处:https://blog.csdn.net/qewgd/article/details/85949278
本文归作者【老铁123】和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
二分查找
针对已有序的序列进行的高效查找,时间复杂度0(n)
实现代码
public class BinarySearch {
/**
* 二分查找 递归
*
* @param num
* @param target
* @return
*/
public static int binarySearchByRecursion(int[] num, int low, int high, int target) {
if (low > high)
return -1;
int mid = (low + high) / 2;
if (num[mid] == target)
return mid;
else if (num[mid] > target)
return binarySearchByRecursion(num, low, mid - 1, target);
else if (num[mid] < target)
return binarySearchByRecursion(num, mid + 1, high, target);
return -1;
}
/**
* 二分查找 循环
*
* @param num
* @param target
* @return
*/
public static int binarySearcherByCycle(int[] num, int target) {
int low = 0;
int high = num.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (num[mid] == target)
return mid;
else if (num[mid] > target)
high = mid - 1;
else if (num[mid] < target)
low = mid + 1;
}
return -1;
}
}