码迷,mamicode.com
首页 > 编程语言 > 详细

java 折半查找

时间:2020-03-09 01:41:44      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:out   turn   pre   search   return   ret   lfs   print   arch   

public static void main(String[] args) {
        int[] arr = {0,1,2,3,4,5,6,7,8,9,10};
        System.out.println(halfSearch_2(arr,5));
    }

    public static int halfSearch_1(int[] arr,int key){
        int min = 0,
            max = arr.length-1,
            mid = (min + max)/2;
        while (arr[mid] != key){
            if ( key > arr[mid])
                min = mid+1;
            else if (key < arr[mid])
                max = mid-1;
            if (min>max)
                return -1;
            mid = (min + max)/2;
        }
        return mid;
    }

    public static int halfSearch_2(int[] arr,int key){
        int min = 0,
            max = arr.length-1,
            mid;
        while (min<=max){
            mid = (max+min)>>1;
            if ( key > arr[mid])
                min = mid+1;
            else if (key < arr[mid])
                max = mid-1;
            else
                return mid;
        }
        return -1;
    }

  

java 折半查找

标签:out   turn   pre   search   return   ret   lfs   print   arch   

原文地址:https://www.cnblogs.com/hongxiao2020/p/12445950.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!