二分查找Java实现
package Test00;
//二分查找
/*
二分查找又叫做折半查找,要求查找的序列有序,每次查找都取中间位置的值与待查的位置的值比较,如果中间的值比
待查的数值大,则在序列的左半部分继续查找;反之,在右半部分查找。直到查找到关键字位置。
如果没有查找到,则返回-1
* */
public class binarySearch {
public static int binarySearch(int[] arr,int a){
//定义查找函数
int low=0;
int high=arr.length-1;
int mid;//定义中间值
while (low<=high){
//判断循环的条件
mid=(low+high)/2;
if (arr[mid]==a){
return mid;//返回查找到的值得位置
}else if (a>arr[mid]){
//向右查找
low=mid+1;
}else {
//向左查找
high=mid-1;
}
}
/* 如果没有找到 返回-1 */
return -1;
}
public static void main(String[] args) {
int[] arr=new int[]{3,4,6,20,40,45,51,62,70,99,110};
int result = binarySearch(arr, 99);
System.out.println(result);
}
}
运行结果:
"C:\Program Files (x86)\Java\jdk1.8.0_172\bin\java.exe" -javaagent:D:\ideaIU-2018.1.5.win\lib\idea_rt.jar=53752:D:\ideaIU-2018.1.5.win\bin -Dfile.encoding=UTF-8 -classpath "C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\charsets.jar;C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\deploy.jar;C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\ext\access-bridge-32.jar;C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\ext\cldrdata.jar;C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\ext\dnsns.jar;C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\ext\jaccess.jar;C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\ext\jfxrt.jar;C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\ext\localedata.jar;C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\ext\nashorn.jar;C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\ext\sunec.jar;C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\ext\sunjce_provider.jar;C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\ext\sunmscapi.jar;C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\ext\sunpkcs11.jar;C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\ext\zipfs.jar;C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\javaws.jar;C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\jce.jar;C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\jfr.jar;C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\jfxswt.jar;C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\jsse.jar;C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\management-agent.jar;C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\plugin.jar;C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\resources.jar;C:\Program Files (x86)\Java\jdk1.8.0_172\jre\lib\rt.jar;D:\TestDemo\out\production\TestDemo" Test00.binarySearch
9
Process finished with exit code 0
返回需要查找的99的索引位置,为9。
注意:数组组下标从0开始