public class DemoTwoSearch {
/**
* @param args 二分查找法
*/
public static void main(String[] args) {
int [] a=new int[]{1,4,3,2,5,7,9,6};
//由于二分查找法必须要在有顺序的情况下进行的,所以要先对数组进行排序
Arrays.sort(a);
//输入要查找的数
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
display(a);
int result=TwoSearch(a,num);
if(result==-1){
System.out.println("没有找到该值");
}else{
System.out.println("该值的索引为"+result);
}
}
public static int TwoSearch(int []a,int num){
int index;
int min=0;
int max=a.length-1;
int mid;
while(min<max){
mid=(min+max)/2;
if(num>a[mid]){
min=mid+1;
}else if(num<a[mid]){
max=mid-1;
}else{
return mid;
}
}
return -1;
}
public static void display(int []a){
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
System.out.println();
}
}
/**
* @param args 二分查找法
*/
public static void main(String[] args) {
int [] a=new int[]{1,4,3,2,5,7,9,6};
//由于二分查找法必须要在有顺序的情况下进行的,所以要先对数组进行排序
Arrays.sort(a);
//输入要查找的数
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
display(a);
int result=TwoSearch(a,num);
if(result==-1){
System.out.println("没有找到该值");
}else{
System.out.println("该值的索引为"+result);
}
}
public static int TwoSearch(int []a,int num){
int index;
int min=0;
int max=a.length-1;
int mid;
while(min<max){
mid=(min+max)/2;
if(num>a[mid]){
min=mid+1;
}else if(num<a[mid]){
max=mid-1;
}else{
return mid;
}
}
return -1;
}
public static void display(int []a){
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
System.out.println();
}
}