[算法训练营] stack sort

问题描述

利用stack实现insertion sort。

输入

待排序数字序列的个数,以及待排序的数字序列。

输出

已排序的数字序列。

样例输入

10

1 5 4 2 3 9 8 7 2 0

样例输出

0
1
2
2
3
4
5
7
8
9

思路

分为两个栈,栈S储存最终输出的结果,栈R存储待处理的数字。在两个栈之间调用栈的接口实现插入排序即可。

代码

#include <iostream>
#include <stack>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::stack;
using std::vector;

stack<int> sorting(stack<int> myStack);

int main()
{
    int n;
    cin >> n;
    stack<int> myStack;
    for (int i = 0; i < n; i++) {
        int tmp;
        cin >> tmp;
        myStack.push(tmp);
    }
    stack<int> result = sorting(myStack);
    vector<int> answer;
    while (!result.empty()) {
        answer.push_back(result.top());
        result.pop();
    }
    for (auto i = answer.rbegin(); i != answer.rend(); i++)
        cout << *i << endl;
    return 0;
}

stack<int> sorting(stack<int> myStack)
{
    stack<int> result; // 输出栈

    if (myStack.empty()) // 边界情况
        return result;

    int tmp = myStack.top(); // 下一个要插入到result中的数

    myStack.pop();

    while (!myStack.empty() || (!result.empty() && result.top() > tmp)) { // 判断最后的tmp放进去会不会出现无序的情况
        if (result.empty() || result.top() <= tmp) { // 需要保持稳定性且避免重复元素
            // result.empty()的次数等于原序列中,比它左边所有元素小的元素个数
            result.push(tmp);
            tmp = myStack.top();
            myStack.pop();
        } else {
            // else的次数等于原序列的逆序数
            myStack.push(result.top());
            result.pop();
        }
    }

    result.push(tmp); // 放入最后的tmp

    return result;
}

猜你喜欢

转载自www.cnblogs.com/trav/p/10363136.html