美文网首页
二分查找

二分查找

作者: 御都 | 来源:发表于2019-07-23 23:24 被阅读0次

前提是:有序的数组

public class Test03 {
    public static int find(int[] arr,int n){
        int max = arr.length - 1;
        int min = 0;
        int mid = (max + min)/2;
        while(min <= max ){
            if(arr[mid] == n){
                return mid;
            }else if(arr[mid] > n){
                max = mid - 1;
            }else if(arr[mid] < n){
                min = mid + 1;
            }
            mid = (max + min)/2;
        }
        return -1;
    }
    public static void main(String[] args){
        int[] ds = {1,2,4,6,9,13,16};
        System.out.println(find(ds,16));
        System.out.println(find(ds,1));
        System.out.println(find(ds,0));
        System.out.println(find(ds,20));
    }
}

相关文章

网友评论

      本文标题:二分查找

      本文链接:https://www.haomeiwen.com/subject/hhwzlctx.html