//二分查找
//要求: 采用左右顺序存储结构,关键字大小有序排列
public int MidSearch(int[] arr,int number int startIndex int endIndex)
{
if(startIndex>endIndex)
{
return -1;
}
else
{
int mid = (startIndex + endIndex)/2;
if(arr[mid]>number)
{
return MidSearch(arr,number,startIndex,mid -1);
}
else if(arr[mid]<number)
{
return MidSearch(arr, number,mid+1, endIndex);
}
else
{
return mid;
}
}
}
对于startIndex + endIndex的越界BUG可以利用:
int mid = startIndex+ ((endIndex - startIndex) / 2);
或者:int mid = (startIndex + endIndex) >>> 1;