//递归
public static int binarySearch(int array[],int val,int start,int end){
int mid = (end-start)/2+start;
if(val == array[mid]){
return mid;
}
if(start>=end){
return -1;
}
else if(val < array[mid]){
return binarySearch(array,val,start,mid-1);
}else if(val > array[mid]){
return binarySearch(array,val,mid+1,end);
}
return -1;
}
//循环
public static int binarySearch(int array[],int val){
int start = 0;
int end = array.length-1;
int mid = array.length/2;
if(val == array[mid]){
return mid;
}
while(start<=end){
mid = (end-start)/2+start;
if(val < array[mid]){
end = mid-1;
}else if(val > array[mid]){
start = mid+1;
}else{
return mid;
}
}
return -1;
}
public static int binarySearch(int array[],int val,int start,int end){
int mid = (end-start)/2+start;
if(val == array[mid]){
return mid;
}
if(start>=end){
return -1;
}
else if(val < array[mid]){
return binarySearch(array,val,start,mid-1);
}else if(val > array[mid]){
return binarySearch(array,val,mid+1,end);
}
return -1;
}
//循环
public static int binarySearch(int array[],int val){
int start = 0;
int end = array.length-1;
int mid = array.length/2;
if(val == array[mid]){
return mid;
}
while(start<=end){
mid = (end-start)/2+start;
if(val < array[mid]){
end = mid-1;
}else if(val > array[mid]){
start = mid+1;
}else{
return mid;
}
}
return -1;
}