Sei sulla pagina 1di 2

Algorithm 1:

voidReverse(StackS1,size){
inttop=1;
StackS2(size);
while(S1>IsEmpty()){
S2>push(S1>pop());
top++;
}
while(!S1>IsEmpty()){
S1>push(S2>pop());
}
while(top>0){
//O(n)times
intvar1=S1>pop();
inttemp=top;
while(temp>0){
//O(n1)times
S2>push(S1>pop());
temp;
}
S1>push(var1);
while(!S2>IsEmpty()){
//O(n)times
S1>push(S2>pop);
}
top;
}
}
Algorithm 2:
voidReverse(StackS1,size){
inttop=1;
StackS2(size);
while(!S1>IsEmpty()){
//O(n)times
inttemp=S1>pop();
intcount=0;
while(!S2>IsEmpty()){
//O(n1)times
S1>push(S2>pop());
count++;
}
S2>push(temp);
while(count>0){
//O(n)times
S2>push(S1>pop());
count;
}

}
while(!S2>IsEmpty()){
S1>push(S2>pop());
}
}
Analysis:
Both algorithms run in same asymptotic time T(n) = O(n2)+O(n-1) i.e O(n2)

Potrebbero piacerti anche