【发布时间】:2016-05-28 14:33:25
【问题描述】:
我的算法的时间复杂度是否低于O(|2(2 + log3(n)) – 1|)?
还有更优雅的写法吗?
int cantor(int low, int high) {
int gap= (high - low) / 3;
if (high < low)
return 0;
else if (high == low)
return low;
else
return cantor(low, low + gap) + cantor(high - gap, high);
}
运行下面的 Java 程序会产生临界点,其中n = 整数输入,o = 操作数,b = 上限(需要>= o)
n o b
0 1 1.0 <- critical point
1 3 3.0 <- critical point
2 3 5.194250610520971
3 7 7.0 <- critical point
4 7 8.592185156484856
5 7 10.04233615383682
6 7 11.388501221041942
7 7 12.65392426064557
8 7 13.85409969044663
9 15 15.0 <- critical point
10 15 16.099749365620383
11 15 17.159572545935887
12 15 18.184370312969712
13 15 19.178087273270823
14 15 20.143957171877723
15 15 21.08467230767364
16 15 22.0025040190721
17 15 22.899390537770895
18 15 23.777002442083877
19 15 24.636792344342172
20 15 25.480033236937405
21 15 26.30784852129114
22 15 27.1212358323658
23 15 27.92108616334829
24 15 28.708199380893266
25 15 29.48329693358293
26 15 30.2470323529008
27 31 31.0 <- critical point
这里是java代码:
public class recursionTreeTimeComplexity {
static int calls = 0;
static int cantor(int low, int high) {
calls++;
int gap = (high - low) / 3;
if (high < low)
return 0;
else if (high == low)
return low;
else
return cantor(low, low + gap) + cantor(high - gap, high);
}
public static void main(String[] args) {
for (int i = 0; i < 1000; i++) {
calls = 0;
cantor(0, i);
// |(2^log3(n)+2)|-1
System.out.println(i + "\t" + calls + "\t" + Math.abs((Math.pow(2, ((Math.log(i) / Math.log(3)) + 2)) - 1)));
}
}
}
【问题讨论】:
标签: java big-o time-complexity binary-search