二分查找算法
public class BinarySearch {
public static void main(String[] args) {
System.out.println("-----------循环实现二分算法--------------");
int[] arr = {1,3,5,9,11,20};
int key = 20;
int position = commonBinarySearch(arr, key);
if(position == -1){
System.out.println("查找的数为:"+key+",序列中没有该数!");
}else{
System.out.println("查找的数为:"+key+",找到位置为下标:"+position);
}
System.out.println("-----------递归实现二分算法--------------");
int[] array ={1,3,5,9,11,20};
System.out.println( binSearch_2(3,array,0,array.length-1));
System.out.println( binSearch_2(5,array,0,array.length-1));
}
/**
*循环实现二分算法,https://blog.csdn.net/maoyuanming0806/article/details/78176957
*/
public static int commonBinarySearch(int[] arr,int key){
int low = 0;
int high = arr.length - 1;
int middle = 0; //定义middle
if(key < arr[low] || key > arr[high] || low > high){
return -1;
}
while(low <= high){
middle = (low + high) / 2;
if(arr[middle] > key){
//比关键字大则关键字在左区域
high = middle - 1;
System.out.println("中位数"+arr[middle]+"比查找的数"+key+"大,则查找的数在中位数"+arr[middle]+"左边");
}else if(arr[middle] < key){
//比关键字小则关键字在右区域
low = middle + 1;
System.out.println("中位数"+arr[middle]+"比查找的数"+key+"小,则查找的数在中位数"+arr[middle]+"右边");
}else{
return middle;
}
}
return -1; //最后仍然没有找到,则返回-1
}
/**
*递归实现二分算法
*/
public static int binSearch_2(int key,int[] array,int low,int high){
//防越界
if (key < array[low] || key > array[high] || low > high) {
return -1;
}
int middle = (low+high)/2;
if(array[middle]>key){
//大于关键字
//比关键字大则关键字在左区域
return binSearch_2(key,array,low,middle-1);
}else if(array[middle]<key){
//小于关键字
//比关键字小则关键字在右区域
return binSearch_2(key,array,middle+1,high);
}else{
return middle;
}
}
}
结果图: