#include <iostream>
#include <stack>
void print(std::stack<int> &stk);
void sort(std::stack<int> &stack);
int main()
{
std::stack<int> stk; //help 栈底存储数值比较大的, stk栈底存储比较小的
int arr[8] = { 2, 5, 1, 15, 19, 11, 25, 17 };
int *beg = std::begin(arr);
int *end = std::end(arr);
while (beg != end)
{
stk.push(*beg++);
}
std::cout << "Before sort: " << std::endl;
print(stk);
beg = std::begin(arr);
while (beg != end)
{
stk.push(*beg++);
}
sort(stk);
std::cout << "After sort: " << std::endl;
print(stk);
system("pause");
return 0;
}
void print(std::stack<int> &stk)
{
while (!stk.empty())
{
std::cout << stk.top() << std::endl;
stk.pop();
}
}
void sort(std::stack<int> &stack)
{
if (stack.empty())
{
return;
}
std::stack<int> help;
int cur = 0;
while (!stack.empty())
{
cur = stack.top();
stack.pop();
while (!help.empty())
{
if (cur > help.top())
{
stack.push(help.top());
help.pop();
}
else
break;
}
help.push(cur);
}
while (!help.empty())
{
stack.push(help.top());
help.pop();
}
}
#include <stack>
void print(std::stack<int> &stk);
void sort(std::stack<int> &stack);
int main()
{
std::stack<int> stk; //help 栈底存储数值比较大的, stk栈底存储比较小的
int arr[8] = { 2, 5, 1, 15, 19, 11, 25, 17 };
int *beg = std::begin(arr);
int *end = std::end(arr);
while (beg != end)
{
stk.push(*beg++);
}
std::cout << "Before sort: " << std::endl;
print(stk);
beg = std::begin(arr);
while (beg != end)
{
stk.push(*beg++);
}
sort(stk);
std::cout << "After sort: " << std::endl;
print(stk);
system("pause");
return 0;
}
void print(std::stack<int> &stk)
{
while (!stk.empty())
{
std::cout << stk.top() << std::endl;
stk.pop();
}
}
void sort(std::stack<int> &stack)
{
if (stack.empty())
{
return;
}
std::stack<int> help;
int cur = 0;
while (!stack.empty())
{
cur = stack.top();
stack.pop();
while (!help.empty())
{
if (cur > help.top())
{
stack.push(help.top());
help.pop();
}
else
break;
}
help.push(cur);
}
while (!help.empty())
{
stack.push(help.top());
help.pop();
}
}