本文实例讲述了Java使用分治算法实现排序数索引功能。分享给大家供大家参考,具体如下:
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
/** * Find the first q and return the index * First method is brutal force * Second may * be Divid and Conquer * * @author open201 * */ public class Ono { /** * f(n) = s.length = n; * * @param s * @param q * @return */ public static int BrutalForceSearch( int [] s, int q) { for ( int i = 0 ; i < s.length; i++) { if (q == s[i]) return i; } return - 1 ; } /** * f(n) = log(n) * * @param s * @param q * @return */ public static int DCSearch( int [] s, int q, int startIndex, int endIndex) { if (startIndex > endIndex) return - 1 ; else { int mid = (startIndex + endIndex) / 2 ; if (s[mid] == q) return mid; else { if (s[mid] > q) return DCSearch(s, q, startIndex,mid- 1 ); else return DCSearch(s, q, mid+ 1 ,endIndex); } } } public static void main(String[] args) { int [] s = new int [ 10000000 ]; for ( int i = 0 ;i< 10000000 ;i++){ s[i] = i; } int q = 10000000 - 1 ; long startTime = System.currentTimeMillis(); System.out.println(BrutalForceSearch(s, q)); long endTime = System.currentTimeMillis(); System.out.println(endTime-startTime); startTime = System.currentTimeMillis(); System.out.println(DCSearch(s, q, 0 , s.length - 1 )); endTime = System.currentTimeMillis(); System.out.println(endTime-startTime); } } |
希望本文所述对大家java程序设计有所帮助。
原文链接:http://blog.csdn.net/baidu_22502417/article/details/46415831