Ch3-6: sorting a stack in an ascending order

本文探讨如何仅使用一个额外栈来模仿选择排序,并通过两个额外栈来模仿归并排序或快速排序。代码实现详细解释了算法逻辑及运行过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

if only use 1 additional stack, then mimic the selection sort.

or with 2 additional stacks, we can mimic merge sort or quick sort.


Full code:

// solution for Ch3-6 by mimicing selection sort
// check CTCI book, it's description is more clear than Hawstein
#include 
#include 
#include 
using namespace std;

stack Ssort(stack s){
	stack t;
	while(!s.empty()){
		int data = s.top();
		s.pop();
		while(!t.empty() && t.top()>data){ // condition 1 will take several inner loop
			s.push(t.top());
			t.pop();
		}
		t.push(data); // condition 2 will take a several outer loop
	}
	return t;
}

int main(){
    srand((unsigned)time(0));
    stack s;

    for(int i=0; i<10; ++i)
        s.push((rand()%100));
    s = Ssort(s);
    while(!s.empty()){
        cout<Executing the program....
$demo 
77 72 71 65 65 43 32 29 10 3 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值