As an exercise I am trying to measure the efficiency of two algorithms that should do the same task, ordering a stack, using only a stack as a support data structure:
#include <stack>
#include <iostream>
#include <chrono>
std::stack<int> sortStack(std::stack<int>& inS){
std::stack<int> tmpS;
int tmpV=0;
tmpS.push(inS.top());
inS.pop();
while(!inS.empty()){
if(inS.top()>=tmpS.top()){
tmpS.push(inS.top());
inS.pop();
}else{
tmpV = inS.top();
inS.pop();
int count = 0;
//reverse the stack until we find the item that is smaller
while(!tmpS.empty()){
if(tmpS.top()>tmpV){
inS.push(tmpS.top());
tmpS.pop();
count++;
}else{
break;
}
}
//tmpS.top is smaller (or =) than tmpV
tmpS.push(tmpV);
//and revert the other stack
for(int i=0; i< count; i++){
tmpS.push(inS.top());
inS.pop();
}
}
}
return tmpS;
}
std::stack<int> sortStackRevisited(std::stack<int>& inS){
std::stack<int> tmpS;
int tmpV=0;
while(!inS.empty()){
tmpV = inS.top();
inS.pop();
//reverse the stack until we find the item that is smaller
while(!tmpS.empty() && tmpS.top()>tmpV){
inS.push(tmpS.top());
tmpS.pop();
}
tmpS.push(tmpV);
}
return tmpS;
}
int main(){
using namespace std::chrono;
std::stack<int> s1({1,0,123,3,5,89,23,12,1000});
std::stack<int> s({1,0,123,3,5,89,23,12,1000});
auto t1 = high_resolution_clock::now() ;
std::stack<int> ordered = sortStackRevisited(s);
auto t2 = high_resolution_clock::now() ;
std::stack<int> ordered2 = sortStack(s1);
auto t3 = high_resolution_clock::now() ;
std::cout<<"\n";
std::cout<<duration_cast<microseconds>(t2-t1).count()<<" "<<duration_cast<microseconds>(t3-t2).count()<<"\n";
}
running this program I obtain consistently that t2 - t1 is bigger than t3- t2. If I change the order of the function calls, i.e:
auto t1 = high_resolution_clock::now() ;
std::stack<int> ordered = sortStack(s);
auto t2 = high_resolution_clock::now() ;
std::stack<int> ordered2 = sortStackRevisited(s1);
auto t3 = high_resolution_clock::now() ;
I still get that t2 - t1 is bigger than t3- t2. What is happening? Am I missing something?
To compile I use g++ --std=c++11 sortStack.cpp