递归查找
二分查找
给定已排好序的n个元素s1,…,sn,现要在这n个元素中找出一特定元素x。要求采用分治法求解,即将问题分解为若干个规模较小、相互独立、与原问题形式相同的子问题;采用递归和非递归两种方式实现。
import java.util.Scanner;
public class Bs {
public static void Bs1(int[]a,int x,int low,int high)
{
if(low<=high)
{
int mid=(low+high)/2;
//System.out.println(a[mid]);
if(x==a[mid])
System.out.println("恭喜你找到了"+x+"为第"+(mid+1)+"个数");
if(a[mid]>x){
high=mid-1;
Bs1(a,x,low,high);
}
else if(a[mid]<x){
low=mid+1;
Bs1(a,x,low,high);
}
}
else{
System.out.println("未找到"+x);
}
}
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int[] A=new int[]{1,2,3,4,5,6,7,9,10};
System.out.print("目前数组为:");
for(int i=0;i<=A.length-1;i++)
System.out.print(" "+A[i]);
System.out.println("请输入要查找的数");
int x=in.nextInt();
Bs1(A,x,0,A.length-1);
}
}