1. 程式人生 > >棧排序,佇列排序

棧排序,佇列排序

同學給我出了一個棧排序的題,意思給一個包含無序數的棧,讓輸出一個順序排列的棧。

直接排序是不可能的,棧只能在一端進行操作。因此需要藉助輔助棧。

思路是將原棧s的資料壓入輔助棧s2,輔助棧用於儲存最終結果。輔助棧中的元素是有序的。

壓棧過程需要比較兩個棧棧頂元素大小關係。如果s棧頂小於s2的棧頂元素,則需要找到s2的棧中第一個大於s1棧頂的元素,然後將s2中的元素出棧到s中。最後將s一開始的那個棧頂元素放入s2。

實現完棧以後,再想想佇列也可以排序嘛,就寫了個佇列排序的演算法。有些粗糙,感覺可以改進。

#include <iostream>
#include <stack>
#include <queue>
using namespace std;

stack<int> stackSort(stack<int> s)
{
    stack<int> s2;  //輔助棧
    
    while(!s.empty())
    {
        int tmp = s.top();
        s.pop();

        while(!s2.empty() && tmp <= s2.top())  //找到輔助棧中第一個小於tmp的元素
        {
            s.push(s2.top());
            s2.pop();
        }
        s2.push(tmp);
    }
   /* while(!s2.empty())
    {
        cout<<s2.top()<<" ";
        s2.pop();
    }
    cout<<endl;*/
    

    return s2;
}

queue<int> queueSort(queue<int> q)
{
    queue<int> q2;

    while(!q.empty())
    {
        int tmp = q.front();
        q.pop();
        int i=0;
        int len = q2.size();
        while(!q2.empty() && tmp > q2.front() && i<len)  //將佇列中的元素依次放入輔助佇列
        {
            q2.push(q2.front());
            q2.pop();
            i++;
        }
        q2.push(tmp);
        while (i<len)    //挪動len-i次,保持輔助佇列的有序性
        {
            q2.push(q2.front());
            q2.pop();
            i++;
        }    
    }
    
    /*while(!q2.empty())
    {
        cout<<q2.front()<<" ";
        q2.pop();
    }
    cout<<endl;*/
    return q2;
}

int main()
{
    stack<int> s;
    s.push(1);
    s.push(5);
    s.push(3);
    s.push(2);
    s.push(4);
    s.push(6);
    stackSort(s);

    queue<int> q;
    q.push(1);
    q.push(7);
    q.push(3);
    q.push(2);
    q.push(4);
    q.push(6);
    q.push(9);

    queueSort(q);
    
    
    system("pause");
    return 0;
}