二分查找

 1 public class BinarySearch 
2 {
3
4 public static int search(int[] array, int n)
5 {
6 int low = 0, mid = 0;
7 int high = array.length - 1;
8
9 while (low <= high) {
10
11 mid = (low + high) >> 1;
12
13 if (array[mid] == n)
14 return mid;
15
16 if (array[mid] > n)
17 high = mid - 1;
18 else
19 low = mid + 1;
20 }
21
22 return -1;
23 }
24
25
26 public static void main(String[] args)
27 {
28 int[] array = new int[100];
29
30 for (int i = 0; i < 100; i++) {
31 array[i] = 100 + i;
32 }
33
34 int result = BinarySearch.search(array, 198);
35
36 System.out.println(result);
37 }
38
39 }

你可能感兴趣的:(二分查找)