算法原理
搜索过程从数组的中间元素开始,如果中间元素正好是要查找的元素,则搜索过程结束;如果某一特定元素大于或者小于中间元素,则在数组大于或小于中间元素的那一半中查找,而且跟开始一样从中间元素开始比较。如果在某一步骤数组为空,则代表找不到。这种搜索算法每一次比较都使搜索范围缩小一半。如果插入排序涉及到较大数据量,可应用到插入排序中。
代码实现
public void testBinarySearch() {
int[] data = {1,2,3,4,5,6,7,7,8};
int index = binarySearchWithRecursive(data, 0, data.length - 1, 7);
if (index == -1) {
System.out.println("Not Found");
} else {
System.out.println("Binary Search Result: " + data[index]);
}
index = binarySearchWithWhileLoop(data, 0, data.length, 8);
System.out.println("WhileLoop Search: " + data[index]);
}
public static int binarySearchWithRecursive(int[] array, int start, int end, int key) {
if (start > end) {
return -1;
}
int mid = (start + end) / 2;
if (array[mid] == key) {
return mid;
}
if (array[mid] < key) {
return binarySearchWithRecursive(array, mid + 1, end, key);
}
return binarySearchWithRecursive(array, start, mid - 1, key);
}
public static int binarySearchWithWhileLoop(int[] array, int start, int end, int key) {
int index = -1;
while (start <= end) {
int mid = (start + end) / 2;
if (array[mid] == key) {
return mid;
}
if (array[mid] < key) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return index;
}
循环版
public static int loopFind(int[] data, int start, int end, int target) {
while (start <= end) {
int mid = (start + end) / 2;
if (data[mid] == target) {
return mid;
}
if (data[mid] < target) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return -1;
}
递归
public static int recurFind(int[] data, int start, int end, int target) {
if (start > end) {
return -1;
}
int mid = (start + end) / 2;
if (data[mid] == target) {
return mid;
}
if (data[mid] < target) {
return recurFind(data, mid + 1, end, target);
}
return recurFind(data, start, mid - 1, target);
}
测试代码
@Test
public void testBS() {
int[] data = {1, 2, 3, 4, 5, 6, 7};
System.out.println(loopFind(data, 0, data.length, 0));
System.out.println(recurFind(data, 0, data.length, 0));
}