C++ 尝试计算算法的运行时间
我有以下算法:C++ 尝试计算算法的运行时间,c++,algorithm,runtime,big-o,time-complexity,C++,Algorithm,Runtime,Big O,Time Complexity,我有以下算法: for(int i = n; i > 0; i--){ for(int j = 1; j < n; j *= 2){ for(int k = 0; k < j; k++){ ... // constant number C of operations } } } for(int i=n;i>0;i--){ 对于(int j=1;j
for(int i = n; i > 0; i--){
for(int j = 1; j < n; j *= 2){
for(int k = 0; k < j; k++){
... // constant number C of operations
}
}
}
for(int i=n;i>0;i--){
对于(int j=1;j
我需要计算算法的运行时间复杂性
我很确定外循环运行O(n)
次,中间循环运行O(log(n))
次,内循环也运行O(log(n))
次,但我不太确定
运行时复杂性的最终结果是O(n^2)
,但我不知道如何实现
希望有人能给我一个简短的解释,谢谢 对于每个
i
,第二个循环通过2的幂运行j
,直到它超过n
:1,2,4,8,2h,其中h=int(log2n)。所以最里面的循环体运行20+21+…+2h=2h+1-1次。2h+1-1=2int(log2n)+1-1,即O(n)
现在,外部循环执行n次。这就给出了整个事情的复杂性O(n*n)