java算法之二分查找

package com.hym.test.algorithms;

public class BinarySerch {
	int[] arrayTest = { 1, 2, 5, 9, 23, 26, 46, 62, 783 };

	public int searchByCycle(int theFindNum) {
		int length = arrayTest.length;
		int begin = 0;
		int end = length - 1;

		while (true) {
			int middle = (begin + end) / 2;
			if (arrayTest[middle] == theFindNum) {
				return middle;
			} else if (begin > end) {
				return length;
			} else {
				if (theFindNum < arrayTest[middle]) {
					end = middle - 1;
				} else if (theFindNum > arrayTest[middle]) {
					begin = middle + 1;
				}
			}
		}
	}

	public int searchByRecursive(int theFindNum, int begin, int end) {
		int middle = (begin + end) / 2;
		if (arrayTest[middle] == theFindNum) {
			return middle;
		} else if (begin > end) {
			return arrayTest.length;
		} else {
			if (theFindNum < arrayTest[middle]) {
				end = middle - 1;
			} else if (theFindNum > arrayTest[middle]) {
				begin = middle + 1;
			}
			return searchByRecursive(theFindNum, begin, end);
		}
	}

	public static void main(String[] args) {
		BinarySerch search = new BinarySerch();
		System.out.println(search.searchByRecursive(9, 0,
				search.arrayTest.length - 1));
	}

}


二分查找又称折半查找,优点是比较次数少,查找速度快,平均性能好;其缺点是要求待查表为有序表,且插入删除困难。因此,折半查找方法适用于不经常变动而查找频繁的有序列表。首先,假设表中元素是按升序排列,将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。

http://baike.baidu.com/view/610605.htm

你可能感兴趣的:(java算法)