I'm trying to figure out amortised analysis of this loop and I can't figure out how to prove that complexity is $O(n \log n)$.
Operation OP(S,X[i])
has complexity O(log|S|)
and operations push
and pop
has constant complexity O(1)
.
S <- Emptystack
for i=1 to n do
while (S!=0) and OP(S,X[i]) do
pop(S)
od
push(S,X[i])
od
I would like to proove it using potential function. It would be simple if there were just pop(S)
and push(s)
:
Pot.function represents number of items in stack
C^ PUSH = 1 + |S|+1 - |S| = 2
C^ POP = 1 + |S|-1 - |S| = 0
So the complexity would be linear (O(2n)) = O(n)
. But I don't know how to compute amortized complexity of OP
.