java 折半查找
1
package com.test2;
2
3
public class Demo2 {
4
5
/**
6
* @param args
7
*/
8
9
public static int search(int[] arrays, int target) {
10
11
int start = 0;
12
int end = arrays.length - 1;
13
int pos;
14
while (start <= end) {
15
pos = (start + end) / 2;
16
if (arrays[pos] == target) {
17
return pos;
18
} else if (arrays[pos] > target) {// 如果數組中間的數大于目標,則將end的位置變成數組中間位置-1的位置
19
end = pos - 1;
20
} else {
21
start = pos + 1;// 如果數組中間的數小于目標,則將start的位置變成數組中間位置+1的位置
22
}
23
}
24
return -1; // 若沒有查找到,則返回-1
25
}
26
27
public static void main(String[] args) {
28
int[] arrays = { 2, 3, 28, 39, 59, 288, 322, 324, 2323 };
29
System.out.println(search(arrays, 28));
30
System.out.println(search(arrays, 322));
31
System.out.println(search(arrays, 59));
32
System.out.println(search(arrays, 288));
33
}
34
35
}
36

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

35

36

posted on 2012-11-17 08:30 skylight 閱讀(196) 評論(0) 編輯 收藏 所屬分類: java