- 二分法
- 作用于一个已经排序的数组(升序),一般用于挑选或查找出一个数字
- 一般有3个变量:最左(left)、最右(right)、中间值(mid=(left+right)/2)
- 结束条件:
- 当mid等于用户需要查找的数字的时候,循环结束
- 当left > right或者查找的数字不在数组中
package exercise03;
import java.util.Scanner;
public class binarySearch {
public static void main(String[] args) {
int[] arr = {1,5,12,36,55,78,98};
int left = 0;
int right = arr.length;
Scanner scanner = new Scanner(System.in);
System.out.print("请输入想要查询的数字: ");
int x = scanner.nextInt();
int i = binarySea(arr,left, right, x);
if (i != -1)
System.out.println(x+"在数组中的下标:"+i);
}
public static int binarySea(int[] a ,int left ,int right , int x)
{
if (right >= left){
int mid = (right + left)/2;
if (a[mid] == x){
return mid;
}
else if (a[mid] > x){
return binarySea(a ,left ,mid-1 ,x);
}else{
return binarySea(a ,mid+1 ,right ,x);
}
}else {
System.out.println("数组不存在");
return -1;
}
}
}