How to Sort a List in C++ STL?
Last Updated :
21 Apr, 2024
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;
}
OutputList 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)
Share your thoughts in the comments
Please Login to comment...