插入排序(C++两个栈)

#include<iostream>
#include<stack>
using namespace std;
/*
通过使用两个栈,来实现插入排序
result      排好序的栈
randomstack 随机生成的乱序的栈
①弹出乱序的栈顶元素,赋值给tmp后并pop()删除
②若result栈为空或者result栈顶元素<=tmp,把tmp压入result栈,更新tmp;
若result栈不为空且result栈顶元素大于tmp,则把大于tmp的元素依次
pop()到randomstack栈,直至result栈为空或者result栈顶元素<=tmp,
把tmp压入result栈,更新tmp
*/
stack<int> insertSorting(stack<int> randomstack) {
	stack<int> result;//result为存储,排好序数字的栈
	if (randomstack.empty()) {//特殊情况,输入的栈randomstack为空,直接返回
		return result;
	}
	int tem = randomstack.top();//将乱序的栈顶元素传给tem后,并删除
	randomstack.pop();

	while (!randomstack.empty() ||tem<result.top()) {
		if (result.empty() || result.top() <= tem) {//如果result为空或者result栈顶元素<tem
			result.push(tem); // 直接压栈
			tem = randomstack.top(); //更新tem
			randomstack.pop();
		}
		else
		{
			randomstack.push(result.top());//将大于tem的元素压入待排序的栈中
			result.pop();//并从result栈中删除
		}
	}
	result.push(tem);//while循环结束,说明randomstack为空,且此时tmp大于result栈顶元素;
	return result;
}
int main() {
	stack<int> s;
	s.push(1);
	s.push(100);
	s.push(30);
	s.push(20);
	s.push(10);
	s.push(111);
	s.push(2);
	s.push(0);
	s.push(60);
	s.push(10);
	cout << "排序后\n";
	stack<int>  r;
	r = insertSorting(s);
	while (!r.empty()) {
		cout << r.top();
		cout << '\n';
		r.pop();
	}
	system("PAUSE");
	return 1;
	
}
在这里插入代码片
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值