今天,我学习了二分查找
得益于二分查找的实现原理,它的效率很高
在使用二分查找前,需要对数组进行排序
实现原理是这样子的:
假如我们要查找数组中其和为指定数字的两个元素
我们先检测0下标和最后一个下标的和
如果等于就输出,大于就把right 的index左移一半,小于就右移一半,就这样不断递归调用(注意栈溢出)
描述起来有点抽象,我们直接上代码
import java.security.PublicKey;
import java.util.Arrays;
import java.util.Scanner;
public class main {
/**
* @param args
*/
public static void main(String[] args) {
int count;
int sum;
int [] numArry;
// TODO Auto-generated method stub
Scanner scanner=new Scanner(System.in);
sum=scanner.nextInt();
count=scanner.nextInt();
numArry=new int[count];
for(int i=0;i<count;i++){
numArry[i]=scanner.nextInt();
}
Arrays.sort(numArry);
half_search(numArry, 0, numArry.length-1, sum);
// public static void halfsearch (int [] arry , int left,int right,int middle){
//
// }
}
private static void half_search(int [] numArry,int left,int right,int sum) {
// TODO Auto-generated method stub
/*right=(numArry.length-1-left)/2;*/
//错误判断
if(numArry.length==0||numArry==null||sum>numArry[numArry.length-1]){
System.out.print("error");
}else if(right==left+1&&numArry[left]+numArry[right]!=sum){
half_search(numArry, left+1, numArry.length-1, sum);
}else if(left==numArry.length-1){
return;
}else if(numArry[left]+numArry[right]>sum){ //如果找到的结果大于要找的值,下标左移
System.out.print(left+"=="+right);
half_search(numArry, left, right-(right-left)/2, sum);
}else if(numArry[left]+numArry[right]<sum){ //如果找到的结果小于要找的值,下标右移
half_search(numArry, left, right+(right-left)/2, sum);
}else if (numArry[left]+numArry[right]==sum){
System.out.print(numArry[left]+"+"+numArry[right]+"\n");
left++;
half_search(numArry, left, numArry.length-1, sum);
}
}
}