从未想过巧妙地利用栈可以完成一个插入排序的工作,虽然时间复杂度并不能令人满意,但这人可以作为一个扩展思路的"算法".
#include<iostream>
#include<stack>
using namespace std;
//利用两个Stack进行排序 这个算法的构思的却巧妙,但是他的时间复杂度可能使我们难以接受的
//在渐进的意义上,其时间复杂度是 O(n²),空间复杂度是O(n)
stack<int> stackSort(stack<int> source)
{
stack<int> dest;//设置一个栈用于保存排序结果
if (source.empty())//如果待排序的栈是空的,那么认为source栈就是有序的
{
return dest;//直接返回一个空栈作为结果
}
//若不是上述情况
int temp = source.top();//那么首先将待排序的栈结构的栈顶元素取出
source.pop();//弹栈
//转而处理其接续状况
while (!source.empty() || (!dest.empty() && dest.top() > temp))//如果待排序的栈非空 或者 结果栈的栈顶元素大于等于当前待排序栈的栈顶元素
{
if (dest.empty() || dest.top() <= temp)//如果结果栈为空或者结果栈的栈顶元素小于待排序的元素
{
dest.push(temp);//直接将新取出的元素压入
temp = source.top();//temp临时空间存入待排序栈的新栈顶元素
source.pop();//待排序栈弹出顶部元素
}
else //如果不满足上述情况,也就是的确需要找到一个位置将元素插入
{
source.push(dest.top());//借用source栈作为辅助空间转存栈顶那些大于temp的元素
dest.pop();//弹栈,转而进入一个循环直到栈有序
}
}
dest.push(temp);//最后,将唯一被剩下的,就是理应为最大值的元素也压入栈中
//事已至此,dest栈就是一个有序的,而且(稳定/不稳定 <这个问题留给你自己去考究>)的排序序列
return dest;
}
int main()
{
stack<int>sour;
stack<int>dest;
for (int i = 0; i < 10; i++)
{
int x;
cin >> x;
sour.push(x);
}
dest = stackSort(sour);
while (!dest.empty())
{
cout << dest.top() <<"\t";
dest.pop();
}
system("pause");
return 0;
}