二分查找的非递归和递归实现
程序员文章站
2024-03-19 15:37:58
...
package test;
public class searchBinary {
/**
*
* @param array
* @param value
* @return
* 最坏情况下,关键词比较次数为log2(n+1),且期望时间复杂度为O(log2n)
*/
public static int binarySearch(int[] array, int value) {
/**
* 非递归
*/
int low,high,mid;
low = 0;
high = array.length - 1;
while(low <= high){
mid = low+(high-low)/2;
if(array[mid] == value){
return mid;
}
if(array[mid] > value){
high = mid - 1;
}
if(array[mid] < value){
low = mid + 1;
}
}
return -1;
}
public static int binarySearchRecursion(int[] array, int value) {
/**
* 递归
*/
int low,high;
low = 0;
high = array.length - 1;
return seaarchRecursion(array, value,low, high);
}
private static int seaarchRecursion(int[] array, int value, int low, int high) {
int mid = low+(high-low)/2;
if(array[mid] == value)
return mid;
if(array[mid] > value)
return seaarchRecursion(array, value,low,high -1);
if(array[mid] < value)
return seaarchRecursion(array, value,low + 1,high);
return -1;
}
}
package test;
import java.util.Scanner;
public class testSearch {
static int[] array = new int[] {1,2,3,4,5,6,7,8,9,10};
static int value;
public static void main(String[] args) {
System.out.print("排序前:");
print(array);
System.out.print("请输入查找数字:");
Scanner sc= new Scanner(System.in);
value = sc.nextInt(); //获取输入信息;
System.out.print("二分查找结果:");
int index = searchBinary.binarySearch(array,value);
System.out.print("非递归查找下标为" + index);
System.out.print("递归查找下标为" + searchBinary.binarySearchRecursion(array,value));
}
private static void print(int[] array2) {
for(int i = 0;i < array2.length;i++){
System.out.print(array2[i] + " ");
}
System.out.println( );
}
}