二分查找又称折半查找
前提条件: 1 采用顺序存储结构 ;2 待查找序列是有序的
如果待查找序列是有序的,则二分查找是最好的查找算法。
不多说,上代码
普通实现
package com.lyj.search;
public class BinarySearch {
/**
* @param args
*/
public static void main(String[] args) {
int[] array = { 1, 4, 12, 17, 20, 25, 34, 40 };
int index = normalBinarySearch(array, 25);
System.out.println("index: " + index);
}
private static int normalBinarySearch(int[] array, int target) {
// 确定上下界
int lower = 0;
int upper = array.length - 1;
while (lower <= upper) {
// 确定中间位置
int mid = (lower + upper) / 2;
if (target == array[mid]) {
return mid;
} else if (target < array[mid]) {
upper = mid - 1;
} else {
lower = mid + 1;
}
}
// 没有目标值返回-1
return -1;
}
}
递归实现
package com.lyj.search;
public class BinarySearch {
/**
* @param args
*/
public static void main(String[] args) {
int[] array = { 1, 4, 12, 17, 20, 25, 34, 40 };
int index = recursionBinarySearch(array, 0, array.length - 1, 25);
System.out.println("index: " + index);
}
private static int recursionBinarySearch(int[] array, int lower, int upper, int target) {
if (lower <= upper) {
int mid = (lower + upper) / 2;
if (target == array[mid]) {
return mid;
} else if (target < array[mid]) {
return recursionBinarySearch(array, lower, mid - 1, target); // 这里要return
} else {
return recursionBinarySearch(array, mid + 1, upper, target); // 这里要return
}
}
return -1;
}
}