1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| 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; } }
|