码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Search

时间:2015-01-11 06:09:17      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:

public static void main(String[] args)
    {
        System.out.println(GetInsertLocation(new int[]{0,2},-1));
        System.out.println(GetInsertLocation(new int[]{0,2},0));
        System.out.println(GetInsertLocation(new int[]{0,2},1));
        System.out.println(GetInsertLocation(new int[]{0,2},2));
        System.out.println(GetInsertLocation(new int[]{0,2},3));
    }

    /**
     * If key not found, return where it should be inserted.
     */
    private static int GetInsertLocation(int[] array, int key)
    {    
        int iLeft = 0;
        int iRight = array.length - 1;
        while(iLeft<=iRight)
        {
            int iMid = (iLeft+iRight)/2;
            if(key==array[iMid])
                return iMid;
            if(key<array[iMid])
                iRight = iMid -1;
            else
                iLeft = iMid +1;
        }        
        return iLeft;
    }

 

output:

0
0
1
1
2

Binary Search

标签:

原文地址:http://www.cnblogs.com/neweracoding/p/4216064.html

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