二分法查找的前提数组是有序的
1 package test;
2
3 public class BinarySearch {
4 public static void main(String[] args) {
5 int[] arr = new int[] { 12, 23, 34, 45, 56, 67, 77, 89, 90 };
6 int key = 89;
7 int target = search(arr, key);
8 if (target == -1) {
9 System.out.println("数组中没有此数");
10 } else {
11 System.out.println(key + "在数组arr第" + target + "位");
12 }
13
14 }
15
16 public static int search(int[] arr, int key) {
17 int minIndex = 0;
18 int maxIndex = arr.length - 1;
19 int middleIndex = (minIndex + maxIndex) / 2;
20 while (minIndex <= maxIndex) {
21 if (key < arr[middleIndex]) {
22 maxIndex = middleIndex - 1;
23 } else if (key > arr[middleIndex]) {
24 minIndex = middleIndex + 1;
25 } else {
26 return middleIndex;
27 }
28 }
29 return -1;
30 }
31 }