Horje
How to Sort a List in C++ STL?

In C++, a list is a sequence container provided by the STL library of C++ that provides the features of a doubly linked list and stores the data in non-contiguous memory locations efficiently. In this article, we will learn how to sort a list in C++.

Example:

Input: 
myList = {30, 10, 20, 40, 50};

Output:
// Sorted list
myList = {10, 20, 30, 40, 50};

Sort a List in C++

To sort a std::list in C++, we can use the std::list::sort function. This function sorts the elements stored in a list by changing their position within the list only as a result the original list is modified but the order of equal elements remains preserved.

Syntax to Sort a List in C++

list_Name.sort();

Here, list_Name is the name of the list container and no parameters are passed.

C++ Program to Sort a List

The below program demonstrates how we can use the list::sort() to sort a list in C++.

C++
// C++ program to sort a list

#include <iostream>
#include <list>
using namespace std;

int main()
{
    // Initializing a list of integers
    list<int> myList = { 30, 10, 20, 40, 50 };

    // Printing the list before sorting
    cout << "List before sorting : ";
    for (int num : myList) {
        cout << num << " ";
    }
    cout << endl;

    // Sorting the list
    myList.sort();

    // Printing the list after sorting
    cout << "List after sorting : ";
    for (int num : myList) {
        cout << num << " ";
    }
    return 0;
}

Output
List before sorting : 30 10 20 40 50 
List after sorting : 10 20 30 40 50 

Time Complexity: O(N logN), here N is the size of the list.
Auxiliary Space: O(1)




Reffered: https://www.geeksforgeeks.org


C++

Related
&lt;type_traits&gt; Header in C++ &lt;type_traits&gt; Header in C++
How to Compare Two Lists in C++ STL? How to Compare Two Lists in C++ STL?
How to Copy a List in C++ STL? How to Copy a List in C++ STL?
How to Find the Sum of All Elements in a List in C++ STL? How to Find the Sum of All Elements in a List in C++ STL?
How to Use the Try and Catch Blocks in C++? How to Use the Try and Catch Blocks in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
16