折半查找法

折半查找法的前提下就是排好序的数组。算了,直接上代码吧,思路就是每次都拿中间的数比较,大于中间数的就取后面一段数继续比较,否则就取前面的一段数继续比较

static int[] a={1,3,5,6,9,10,29};//定义一组测试的数组
    static int b=9;//要从数组里面查找的数
    public static void main(String[] args) {
        
        int result = search(0, a.length-1, b);
        System.out.println(result);
        
    }
    public static int search(int start,int end,int value){
        if(a[start]==value){
            return start;
        }
        if(a[end]==value){
            return end;
        }
        if(start>=end||start+1==end||a[start]>value||a[end]<value){
            return -1;
        }
        
        int middle=(start+end)/2;
        if(value>a[middle]){
            start=middle;
            return search(start, end, value);
        }else if(value<a[middle]){
            end=middle;
            return search(start, end, value);
        }else{
            return middle;//找到了
        }
    }

运行结果:

原文地址:https://www.cnblogs.com/pig-brother/p/7364007.html