首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。