【数据结构与算法】二分查找

  • 基本思想

首先将给定的值K与表中中间位置元素比较,若相等,则查找成功;若不等,则所需查找的元素只能在中间数据以外的前半部分或者后半部分,缩小范围后继续进行同样的查找,如此反复,直到找到为止。

  • 代码实现

/**
 * 源码名称:BinarySearch.java 
 * 日期:2014-08-14 
 * 程序功能:二分查找 
 * 版权:CopyRight@A2BGeek
 * 作者:A2BGeek
 */
public class BinarySearch {
	public static int binarySearch(int[] in, int key) {
		int start = 0;
		int end = in.length - 1;
		int index = -1;
		while (start <= end) {
			// int mid = (start + end) / 2;会溢出
			// int mid = start + (end - start) / 2;
			int mid = start + ((end - start) >> 2);
			// int mid = (start + end) >>> 1;
			if (key < in[mid]) {
				end = mid - 1;
			} else if (key > in[mid]) {
				start = mid + 1;
			} else {
				index = mid;
				break;
			}
		}
		return index;
	}

	public static int binarySearchRecursive(int[] in, int key, int start,
			int end) {
		if (start <= end) {
			int mid = start + ((end - start) >> 2);
			if (key < in[mid]) {
				end = mid - 1;
				return binarySearchRecursive(in, key, start, end);
			} else if (key > in[mid]) {
				start = mid + 1;
				return binarySearchRecursive(in, key, start, end);
			} else {
				return mid;
			}
		} else {
			return -1;
		}
	}

	public static void main(String[] args) {
		int[] testCase = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 20, 36 };
		System.out.println(binarySearch(testCase, 12));
		System.out.println(binarySearchRecursive(testCase, 12, 0,
				testCase.length - 1));
	}
}


你可能感兴趣的:(数据结构,二分查找,算法)