递归-二分法查找

1.class BinarySearch {   
2.    public static void main(String[] args) {   
3.        int[] a = {2,3,4,5,6,7,8,9,10,13,17,18,24,56,78};   
4.        System.out.println(search(a,5));   
5.    }   
6.  
7.    private static int search(int[] a, int key) {   
8.        return search(a,0,a.length,key);   
9.    }   
10.  
11.    private static int search(int[] a, int from, int to, int key) {   
12.        if(from > to) return -1;   
13.        int middle = (from + to)/2;   
14.        if (a[middle] == key) return middle;   
15.        if (a[middle] > key) return search(a,from,middle-1,key);   
16.        else return search(a,middle+1,to,key);   
17.    }   
18.}  

你可能感兴趣的:(二分法)