【數據結構與算法】二分查找

  • 基本思想

首先將給定的值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));
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章