Open In App

How to Sort a Deque in C++?

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, the STL provides a container called a double-ended queue which is popularly known as deque. This container allows fast insertions and deletions at both ends of the container. In this article, we will learn how to sort a deque in C++.

Example:

Input:
myDeque = {30, 10, 20,50,40}

Output: 
10 20 30 40 50

Sort Elements in a Deque in C++

We can use the std::sort method provided by the STL library to sort a std::deque in C++. This function sorts the elements in a given range into ascending order by default.

Syntax of std::sort

sort(deque.begin(),  deque.end())

where begin and end are iterators denoting the beginning and the end of the deque.

If we want to change the order, we can provide the custom comparator as third parameter.

C++ Program to Sort a Deque

The following code demonstrates how we can sort a deque in C++:

C++
// C++ program to illustrate how to sort a deque
#include <algorithm>
#include <deque>
#include <iostream>
using namespace std;

int main()
{
    // Initialize a deque
    deque<int> dq = { 30, 10, 20, 50, 40 };

    // Print the original deque
    cout << "Original deque: ";
    for (int x : dq) {
        cout << x << " ";
    }
    cout << endl;

    // Sort the dequue
    sort(dq.begin(), dq.end());

    // Print the sorted deque
    cout << "Sorted deque: ";
    for (int x : dq) {
        cout << x << " ";
    }
    cout << endl;

    return 0;
}

Output
Original deque: 30 10 20 50 40 
Sorted deque: 10 20 30 40 50 

Time Complexity: O(N logN) where N is the number of elements in the deque.
Auxiliary Space: O(logN)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads