美文网首页
二分查找

二分查找

作者: 鸡杂面 | 来源:发表于2019-04-09 17:22 被阅读0次

一.递归实现

public class Binarys {
        public static void main(String[] args) {
            int[] arr = {1,2,3,4,5,6,7,8,9,10,50,60,67,88,99,555,4444};
            int a = binary(arr,4,0,arr.length-1);
            System.out.println(a);
        }
        //二分查找,参数:有序数组,查找数,起始位置,结束位置
        public static int binary(int[] arr,int key,int low,int high) {
                if( key<arr[low] || key>arr[high] || low>high )
                    return -1;
                int middle = (low+high)/2;
                if(key>arr[middle]) {
                    return binary(arr, key , middle,high);
                }else if(key<arr[middle]){
                    return binary(arr, key , low,middle);
                }else {
                    return middle;
                }
        }
}

相关文章

网友评论

      本文标题:二分查找

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