二分查找法(循環和遞歸的兩種實現方法)

package sort;
public class BinaryFind {
	static int[] a = { 1, 2, 4, 6, 8, 9, 10, 40 };
	public static void main(String[] args) {
		System.out.println(binaryFind(3));
		System.out.println(binaryFindRec(3, 0, a.length - 1));
	}
	public static int binaryFind(int key) {
		int lowerBound = 0;
		int upperBound = a.length - 1;
		int current;
		while (true) {
			current = (lowerBound + upperBound) / 2;
			if (a[current] == key) {
				return current;
			} else if (lowerBound > upperBound) {
				return -1;
			} else {
				if (a[current] > key) {
					upperBound = current - 1;
				} else {
					lowerBound = current + 1;
				}
			}
		}
	}
	public static int binaryFindRec(int key, int lowerBound, int upperBound) {
		int current;
		while (true) {
			current = (lowerBound + upperBound) / 2;
			if (a[current] == key) {
				return current;
			} else if (lowerBound > upperBound) {
				return -1;
			} else {
				if (key < a[current]) {
					return binaryFindRec(key, lowerBound, current - 1);
				} else {
					return binaryFindRec(key, current + 1, upperBound);
				}
			}
		}
	}
}
相關文章
相關標籤/搜索