- class ArrayTest
- {
- public static void main(String[] args)
- {
- int[] arr = {0,1,2,3,4,5,6,7,8,9};
- int index = getIndex(arr,11);
- System.out.println("index="+index);
- printArray(arr);
- }
- public static void printArray(int []arr)
- {
- for (int x=0;x<arr.length ;x++ )
- {
- System.out.print(arr[x]+", ");
- }
-
- }
- public static int getIndex(int[] arr,int key)
- {
- int min = 0,max = arr.length-1,mid;
- while(min<=max)
- {
- mid = (max+min)/2;
- if(key>arr[mid])
- min = mid + 1;
- else if(key<arr[mid])
- max = mid - 1;
- else
- return mid;
- }
- return min;
- }
- }
复制代码
我还准备把数值插入再打印 但是发现我不会。。。囧 |