欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

二分查找-递归

程序员文章站 2024-03-17 23:05:58
...
public static int myBinarsSearch(int[] a, int key, int start, int end) {
		//start一定不能大于end
		while (start <= end) {
			int middle = (start + end) / 2;
			if (key == a[middle]) {
				return middle;
			} else if (key > a[middle]) {
				return myBinarsSearch(a, key, middle + 1, end);
			} else if (key < a[middle]) {
				return myBinarsSearch(a, key, start, middle - 1);
			}
		}
		return -1;
	}
	public static void main(String[] args) {
		int[] a = { 1, 5, 6, 2, 8, 11, 99 };
		int result = Er_digui.myBinarsSearch(a, 99, 0, a.length);
		System.out.printf("返回的下标为:%d", result);
	}