已知有序的序列,比如:2,3,3,5,9,9,9,12,12,13,15,22,22,22,22,25,25,23,91,95
有整数x,比如: x=23
要求找到一个刚好比x稍微大一点的元素位置
当数组较大的时候,需要二分查找加快速度。
典型的二分查找问题,定义一个尾指针end和一个头指针begin不断二分递归,当end-begin==1时说明a[begin]一定小于等于x,a[end]一定大于x.end便为所要查询的结果.
二分数据范围:[ a[begin], a[end] )
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[] a = {1, 5, 11, 24, 25, 32, 32, 33, 49, 66, 68, 69, 70, 75, 88, 102, 114, 119, 120, 135, 146, 221, 294, 300, 302, 305, 333};
int x = 32;
int index = fun(a, x);
System.out.println(index);
}
public static int fun(int[] a, int x) {
if (x >= a[a.length - 1]) return -1;
return fun(a, x, 0, a.length); //fun(a[], x, begin, end) [0, a.length)
}
public static int fun(int[] a, int x, int begin, int end) { //包含begin 不包含end [begin, end)
if (end - begin == 1) {
if (a[begin] > x) return begin;
return end;
}
int index = (begin + end)/2;
if (x < a[index]) return fun(a, x, begin, index);
return fun(a, x, index, end);
}
}
github实现:https://github.com/striner/javaCode/blob/master/Binary%20search