public class ArrayHalfSort {
public static int getIndex(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 min;
}
public static void main(String[] args) {
int[] arr={2,4,5,7,9,32,56};
int index=getIndex(arr, 12);
System.out.println("index= "+index);
//
printArray(arr);
}
public static void printArray(int[] arr){
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
if(i!=arr.length-1)
System.out.print(arr[i]+", ");
else System.out.println(arr[i]+"]");
}
}
}
看毕老师视频讲的折半查询一个数后在一个数组中插入该数。可是不会了。。。请教一下,该怎么做才能不覆盖那个角标位的数?
|
|