Java查找算法之二分法查找

前言:讲究的就是一个清晰
原文出处:http://blog.csdn.net/u014158743/article/details/52590544

class Demo
{
    public static void main(String[] args) 
    {
        //二分法查找:前提条件:被查找的数组必须是有序的 

        int[] arr = {23,34,45,56,67,78,89,120};
        int key = 99;

        int index = halfSearch(arr,key);
        System.out.println("index="+index);
    }


    //二分法查找
    //结果:下标或-1
    //参数:数组和被找的数
    public static int halfSearch(int[] arr,int key)
    {
        int min = 0,max = arr.length-1,mid;

        while(min<=max)
        {
            mid = (min+max)>>1;
            if(key>arr[mid])
                min = mid+1;
            else if(key<arr[mid])
                max = mid-1;
            else
                return mid;
        }
        return -1;
    }
}
    原文作者:查找算法
    原文地址: https://blog.csdn.net/u014158743/article/details/52590544
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞