public static void main(String[] args) {
//int[] arr=new int[]{3,5,6,4,2,9};
//int index=getIndex(arr,2);
int[] arr={1,3,5,7,8,9,12,15,36};
int index=halfSearch(arr,32);
System.out.println("index!"+index);
}
/*
折半查找
*/
public static int halfSearch(int[] arr,int key)
{
int min,max,mid;
min=0;
max=arr.length-1;
mid=(max+min)/2
while(arr[mid]!=key)
{
if(key>arr[mid])
min=mid+1;
else if(key<arr[mid])
max=mid-1;
if(min>max)
return -1;
mid=(max+min)/2;
}
return mid;
}
上面只能输出索引位置,怎么做将新数据插入,形成一个新的数组序列呢?
|
|