对分查找算法(迭代和递归方式)
二分查找法是对一组有序的数字中进行查找,传递相应的数据,进行比较查找到与原数据相同的数据,查找到了返回对应的数组下标,失败返回-1。
迭代方式
public static int binarysearch(int[] srcArray, int des){
int low = 0;
int high = srcArray.length-1;
while(low <= high){
int middle = (low + high)/2;
if(des == srcArray[middle]){
return middle;
}else if(des <srcArray[middle]){
high = middle - 1;
}else {
low = middle + 1;
}
}
return -1;
}
递归方式
public static int binarySearch(int[] arr,int first,int last,int des){
int mid=(first+last)/2;
if(first>last)
return -1;
else if(des==arr[mid])
return mid;
else if(des<arr[mid])
return binarySearch(arr, first, mid-1, des);
else
return binarySearch(arr, mid+1, last, des);
}
测试代码
public static void main(String[] args){
System.out.println(binarysearch(src, 32));
System.out.println(binarySearch(src,0,src.length-1,48));
}