[算法訓練營] 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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章