Stack-AVL传输算法

时间:2013-05-03 06:43:06

标签: algorithm analysis

假设我有一个算法从堆栈中弹出每个元素并将它们插入到AVL树中。

If pop () is a O (1) method and insert () is an O(log n) method,  
my algorithm is O(log n), O (n) or O(n log n)?

为什么?

1 个答案:

答案 0 :(得分:2)

您的算法为O(nlogn),或Theta(nlogn)为准确,假设插入为Theta(logn)

i步骤费用c1 + c2*log(i)c1常量pop()c2是AVL插入保证的常量),因此您得到:< / p>

c1 + c2*log(1) + c1 + c2*log(2) + .... + c1 + c2*log(n) = 
= c1*n + c2*log(1*2*...*n) = c1*n + c2*log(n!) <= (for large enough n) (c2+1)*log(n!)

如果我们“忽略”常量它的可读性更高(当然不太准确,必须小心谨慎,但这对直觉有好处):

log(1) + log(2) + ... + log(n) = log(1*2*...*n) = log(n!)
and log(n!) is in O(nlogn)

众所周知,log(n!)位于Theta(nlogn) - 因此这是您的总体复杂性。