折半查询,(数组必须是有序的)
public class Utils {
private static int binaryQueryCompote(int[] buf, int n, int sta, int end) {
if(sta > end) {
return -1;
}
if(sta == end) {
if(buf[sta] == n) {
return sta;
}else {
return -1;
}
}
int i = (end + sta) / 2;
if(buf[i] == n) {
return i;
}else if(buf[i] < n){
return binaryQueryCompote(buf, n, i + 1, end);
}else {
return binaryQueryCompote(buf, n, sta, i - 1);
}
}
public static int binaryQuery(int[] buf, int n) {
return binaryQueryCompote(buf, n, 0, buf.length -1);
}
}
测试类
public class Test {
public static void main(String[] args) {
/*
* 1. 找出数组中的元素
* 2. 如果要使用折半查询,则数组元素必须有序
* */
Scanner scanner = new Scanner(System.in);
int[] buf = {18, 27, 33, 48, 57, 57, 66, 68, 70, 76, 86, 94, 95, 96, 108, 116, 129, 154, 158, 166, 181, 185, 185, 200, 200, 208, 220, 233, 239, 296, 300, 306, 312, 315, 316, 321, 329, 350, 351, 354, 362, 378, 379, 379, 381, 388, 411, 415, 423, 429, 471, 481, 483, 483, 483, 499, 499, 513, 515, 526, 529, 533, 540, 546, 566, 567, 578, 589, 589, 610, 615, 641, 656, 666, 693, 702, 703, 730, 742, 758, 761, 778, 801, 803, 814, 828, 835, 837, 839, 840, 845, 876, 899, 906, 919, 921, 930, 933, 949, 970};
System.out.print("请输入您要查询的数:");
int n = scanner.nextInt();
System.out.println(Utils.binaryQuery(buf, n));
}