递归-二分法查找

二分法查找是建立在针对有序数组的查找,这里使用的是递归的算法,算法本身比较简单,这里就不再叙述。

二分法查找的时间效率为O(log n)

代码如下:

class BinarySearch {
	public static void main(String[] args) {
		int[] a = {2,3,4,5,6,7,8,9,10,13,17,18,24,56,78};
		System.out.println(search(a,5));
	}

	private static int search(int[] a, int key) {
		return search(a,0,a.length,key);
	}

	private static int search(int[] a, int from, int to, int key) {
		if(from > to) return -1;
		int middle = (from + to)/2;
		if (a[middle] == key) return middle;
		if (a[middle] > key) return search(a,from,middle-1,key);
		else return search(a,middle+1,to,key);
	}
}
 

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