二分查找是比较常用也是很高效的一种查找算法,其要求查找数据集的有序,采用顺序存储。在这里使用数组来简单的模拟数据集,并且要求数组升序元素排列,仅仅作为示例使用。如有错误欢迎批评指正。
public class BinarySearch {
/**
* 二分查找迭代版本
*
* @param src原数组从小到大排列
* @param target查找的目标元素位置
* @return当目标元素在数组中不存在的时候返回-1
*/
public static int binarySearch(int[] src, int target) {
int result = -1;
int start = 0;
int end = src.length - 1;
while (end >= start) {
int half = (end + start) / 2;
if (target == src[half]) {
result = half;
break;
} else if (target < src[half]) {
end = half - 1;
} else {
start = half + 1;
}
}
return result;
}
/**
* 二分查找的递归版本
*
* @param src原数组从小到大排列
* @param target查找的目标元素位置
* @return当目标元素在数组中不存在的时候返回-1
*/
public static int binarySearch(int[] src, int target, int start, int end) {
int result = -1;
if (end < start) {
return result;
}
int half = (start + end) / 2;
if (target == src[half]) {
result = half;
} else if (target < src[half]) {
result = binarySearch(src, target, start, half - 1);
} else {
result = binarySearch(src, target, half + 1, end);
}
return result;
}
public static void main(String[] args) {
int[] src = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int pos = binarySearch(src, 6, 0, src.length - 1);
if (pos != -1) {
System.out.println("找到目标点在" + pos + "位置,值为" + src[pos]);
} else {
System.out.println("没有找到目标点");
}
}
}