二分查找 while & 递归
作者:互联网
目录
简介
二分查找算是 一种分治思想的体现,能在最坏时间复杂度O(logn)下查找出元素,但是,有一个重要的前提就是要提前排好序
二分查找复杂度
O(logn)
while版
public int binarySearch(int[] nums, int key) {
if (nums.length < 1 || key < nums[0] || key > nums[nums.length - 1]) {
return -1;
}
int start = 0;
int end = nums.length - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (key < nums[mid]) {
end = mid - 1;
} else if (key > nums[mid]) {
start = mid + 1;
} else {
return mid;
}
}
return -1;
}
递归版
public int binarySearch(int[] nums, int key, int l, int r) {
int n = nums.length;
if (n < 1 || key < nums[0] || key > nums[n - 1]) {
return -1;
}
int mid = (l + r) / 2;
if (nums[mid] == key) {
return mid;
} else if (nums[mid] > key) {
binarySearch(nums, key, l, mid - 1);
} else {
binarySearch(nums, key, l + 1, r);
}
return -1;
}
标签:二分,return,递归,nums,int,mid,binarySearch,while,key 来源: https://www.cnblogs.com/worldline/p/15556173.html