首页 > 代码库 > Binary Search

Binary Search

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