经典面试题:请手写一个二分查找法
二分查找又称折半查找,它是一种效率较高的查找方法。
1.二分查找要求:
(1)必须采用顺序存储结构
(2).必须按关键字大小有序排列
2.二分查找法原理:
3.二分查找Jdk8源码:
// Like public version, but without range checks.
private static int binarySearch(int[] a, int fromIndex, int toIndex,
int key) {
int low = fromIndex;
int high = toIndex - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = a[mid];
if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
4.递归实现二分查找:
//递归实现二分查找
private static int binarySearchDiGui(int[] arr, int data, int beginIndex, int endIndex) {
if (arr == null) {
return -1;
}
int midIndex = (beginIndex + endIndex) >>> 1;
if (data < arr[beginIndex] || data > arr[endIndex] || beginIndex > endIndex) {
return -1;
}
if (data > arr[midIndex]) {
//递归,如果查找的数据大于中值,则以中值+1为起始索引查找
return binarySearchDiGui(arr, data, midIndex + 1, endIndex);
}
if (data < arr[midIndex]) {
//递归,如果查找的数据大于中值,则以中值+1为起始索引查找
return binarySearchDiGui(arr, data, beginIndex, midIndex - 1);
} else {
return midIndex;
}
}