package oo3_binary_search;
import java.util.Arrays;
import java.util.Scanner;
/**
* @author ALazy_cat
* 二分查找:要求待查表有序。二分查找的基本思想是将n个元素分成大致相等的两部分,取 a[n/2]与x做比较,
* 如果x=a[n/2],则找到x,算法中止;如果x<a[n/2],则只要在数组a的左半部分继续搜索x,如果x>a[n/2],则
* 只要在数组a的右半部搜索x.
*/
public class BinarySearch {
public static void main(String[] args) {
int[] a = { 0, 10, 19, 24, 73, 94, 95 };
int pos = 0;
System.out.println("数组: " + Arrays.toString(a));
Scanner in = new Scanner(System.in);
System.out.print("请输入关键字: ");
int key = in.nextInt();
in.close();
System.out.println("在数组中搜索数字 " + key + "...");
if ((pos = binarySearch1(a, key)) != -1) {
System.out.println(key + " 在数组中的位置是: " + pos);
} else {
System.out.println(key + "不存在.");
}
System.out.println("---------------------");
System.out.println("在数组中搜索数字 " + key + "...");
if ((pos = binarySearch2(a, key)) != -1) {
System.out.println(key + " 在数组中的位置是: " + pos);
} else {
System.out.println(key + "不存在.");
}
}
// 二分查找的递归实现
// 如果在有序表中有满足a[i] == key的元素存在,则返回该元素的索引i;否则返回-1
public static int binarySearch1(int[] a, int key) {
return binarySearch1(a, key, 0, a.length - 1);
}
public static int binarySearch1(int[] a, int key, int low, int high) {
if (low > high)
return -1;
int mid = (low + high) / 2;
if (a[mid] == key) {
return mid;
} else if (a[mid] < key) {
return binarySearch1(a, key, mid + 1, high);
} else {
return binarySearch1(a, key, low, mid - 1);
}
}
// 二分查找的循环实现
// 循环条件:low<=high;
// 循环体:改变low与high的值即可
public static int binarySearch2(int[] a, int key) {
int low = 0;
int high = a.length - 1;
int mid = 0;
while (low <= high) {
mid = (low + high) / 2;
if (a[mid] == key) {
return mid;
} else if (a[mid] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
}