二分法查找

不用多说了,有点必须提下,查找前数组必须排序

public class BinarySearch {

	public BinarySearch() {
	}

	public static int binarySearch(int[] datas, int key) {
		int index = -1;
		int low = 0;
		int high = datas.length - 1;
		while (low <= high) {
			int middle = (low + high) >> 1;
			if (key == datas[middle]) {
				index = middle;
				break;
			} else if (key > datas[middle]) {
				low = middle + 1;
			} else if (key < datas[middle]) {
				high = middle - 1;
			}
		}
		return index;
	}

	public static void main(String[] args) {
		int[] datas = { 1, 2, 3, 4, 5, 6 };
		int index = BinarySearch.binarySearch(datas, 6);
		System.out.println(index);
	}
}

 

你可能感兴趣的:(二分法)