How to sort a C++ queue in ascending order?

To use a C++ queue to implement sorting from smallest to largest, you can follow these steps:

  1. First, insert the original data into the queue in sequence.
  2. Next, create a secondary queue and insert the first element from the original queue into the secondary queue.
  3. Next, the second element is removed from the original queue and compared sequentially with the elements in the auxiliary queue. If the element in the original queue is smaller than the element in the auxiliary queue, it is inserted into the appropriate position in the auxiliary queue. If the element in the original queue is larger than the element in the auxiliary queue, the elements in the auxiliary queue are inserted into the original queue one by one, and the element in the original queue is inserted into the appropriate position in the auxiliary queue.
  4. Repeat step 3 until the original queue is empty.
  5. Ultimately, the elements in the auxiliary queue are the result of being sorted from smallest to largest.

Here is a sample code snippet:

#include <iostream>
#include <queue>

using namespace std;

void sortQueue(queue<int>& q) {
    queue<int> temp;
    while (!q.empty()) {
        int current = q.front();
        q.pop();
        while (!temp.empty() && temp.back() > current) {
            q.push(temp.back());
            temp.pop();
        }
        temp.push(current);
    }
    q = temp;
}

int main() {
    queue<int> q;
    q.push(5);
    q.push(2);
    q.push(8);
    q.push(1);
    q.push(3);

    cout << "原始队列:";
    while (!q.empty()) {
        cout << q.front() << " ";
        q.pop();
    }
    cout << endl;

    sortQueue(q);

    cout << "排序后的队列:";
    while (!q.empty()) {
        cout << q.front() << " ";
        q.pop();
    }
    cout << endl;

    return 0;
}

The output is:

原始队列:5 2 8 1 3 
排序后的队列:1 2 3 5 8 
bannerAds