二分查找法的两种形式-递归和非递归,递归形式简单,但是在数量大时所消耗的时间空间也极大,下面以Java代码给出两种形式的具体实现
1)非递归
public class BinarySearch{
public static void main(String[] args){
//有时间补上传入浮点数异常的情况
}
//-1代表未成功查找
public static int search(int key,int[] a){
if(a.length<=0){
return -1;
}
else
{
int start = 0;
int end = a.length-1;
while(start<=end){
mid = (start + end)/2;
if(a[mid]==key)
return mid;
else if(a[mid]>key)
end = mid-1;
else
start = mid+1;
}
return -1;
}
}
}
2)递归
public class BinarySearch{
public static void main(String[] args){
int[] a = {1,2,3,4,5}
start = 0;
end = a.length - 1;
k = 8;
search(k,a,start,end);
//有时间补上传入浮点数异常的情况
}
//-1代表未成功查找
public static int search(int key,int[] a,int start,int end){
if(start > end){
return -1;
}
else
{
int mid = (start+end)/2;
if(a[mid]==key)
return mid;
else if(a[mid]>key)
search(key,a,start,mid-1)
else if(a[mid]<key)
search(key,a,mid+1,end)
}
}
}
2018-01-28