折半查找,也称二分查找,在某些情况下相比于顺序查找,使用折半查找算法的效率更高。 但是该算法的使用前提是静态查找表中的数据必须是有序的。
下面来看代码:
代码语言:javascript复制public class Main {
public static int Max = 20;
public static int data[] = { 12, 16, 19, 22, 25, 32, 39, 39, 48, 55, 57,58,63, 68, 69, 70, 78, 84, 88, 90, 97 };
public static int count = 1;
public static void main(String[] args) {
System.out.println("请输入您要查找的数字:");
Scanner sc = new Scanner(System.in);
int KeyValue = sc.nextInt();
if (Search(KeyValue)) {
System.out.println("共查找了" count "次");
} else {
System.out.println("抱歉,数据数组源中找不到您输入的数字");
}
}
public static boolean Search(int k) {
int left = 0;
int right = Max - 1;
int middle;
while (left <= right) {
middle = (left right) / 2;
if (k < data[middle]) {
right = middle - 1;
} else if (k > data[middle]) {
left = middle 1;
} else if (k == data[middle]) {
System.out.println("Data[" middle "] = " data[middle]);
return true;
}
count ;
}
return false;
}
}