二分查找又称为折半查找,二分查找的关键在于,给出的一列数,必须是有序的排列,该算法的时间复杂度O(n)=O(log2^n)。假设一个数组为升序排列,通过每次找中间索引的值,来和我们要查找的数来进行比较,如果中间值大于所查找的值,则说明该值在中间值的左边,因此再从左边的数组继续寻找中间值,直到找出该数为止。我们来通过代码来作以解释:
import java.util.Scanner;
public class MyDemo {
public static void main(String[] args) {
//必须为有序数组
int[] ints = new int[]{2,5,8,45,78,89};
System.out.println("输入你要查询的数:");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
String id = findnum(ints, i);
if (id.equals(null)){
System.out.println("数组中没有该数字");
}else {
System.out.println("你要查询的数的索引为" + id);
}
}
private static String findnum(int arr[],int key) {
int low=0;
int high=arr.length-1;
while (low<=high){
//找出中间索引
int mid=(low+high)/2;
//比较中间索引上的值和要查找的值的大小
if (arr[mid]>key){
high=mid-1;
}else if (arr[mid]<key){
low=mid+1;
}else {
return String.valueOf(mid);
}
}
//未查找到返回null
return null;
}
}
查询45可得到编译结果:
输入你要查询的数:
45
你要查询的数的索引为3