The sort() function is used to sort elements in a container or array. It provides a simple and efficient way to sort data in C++.
- Works on random-access iterators (arrays, vectors, deques).
- Default sort is ascending order.
#include <iostream>
using namespace std;
int main()
{
vector<int> v = {5, 3, 2, 1, 4};
// Sort vector (by default in ascending order)
sort(v.begin(), v.end());
for (int i : v)
cout << i << " ";
return 0;
}
Output
1 2 3 4 5
Syntax of sort()
The std::sort() function is defined inside the <algorithm> header file.
sort(first, last);
Parameters:
- first: Iterator to the beginning of the range to be sorted.
- last: Iterator to the element just after the end of the range.
Variations and Usage of sort() in C++ STL
Sort the entire range (default ascending order)
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
int arr[5] = {5, 3, 2, 1, 4};
int n = sizeof(arr) / sizeof(arr[0]);
// Sort array (by default in ascending order)
sort(arr, arr + n);
for (int i : arr)
cout << i << " ";
return 0;
}
Output
1 2 3 4 5
Sort a specific range
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
int arr[] = {10, 5, 8, 1, 7, 3};
int n = sizeof(arr) / sizeof(arr[0]);
// Sort only the elements from index 1 to 4 (i.e., 5, 8, 1, 7)
sort(arr + 1, arr + 5);
// Print the array after sorting the range
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
Output
10 1 5 7 8 3
Sort Array in Descending Order
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
int arr[5] = {5, 3, 2, 1, 4};
int n = sizeof(arr) / sizeof(arr[0]);
// Sort array in descending order
sort(arr, arr + n, greater<int>());
for (int i : arr)
cout << i << " ";
return 0;
}
Output
5 4 3 2 1
Sort Vector of User Defined Type
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
struct Point
{
int x;
int y;
};
int main()
{
vector<Point> points = {{3, 5}, {1, 2}, {4, 1}};
// Sort points by x value (ascending)
sort(points.begin(), points.end(), [](const Point &a, const Point &b) { return a.x < b.x; });
// Print sorted points
for (auto p : points)
cout << "(" << p.x << "," << p.y << ") ";
return 0;
}
Try it on GfG Practice
Output
(1,2) (3,5) (4,1)
Working of sort() Function
The sort() function is implemented using the Intro Sort Algorithm. It is the combination of three standard sorting algorithms: insertion sort, quick sort and heap sort. It automatically chooses the best algorithm that fits the given case. Refer to this article to know more - Internal Working of STL sort() Function.
As it uses the above sorting algorithms, its average time complexity turns out to be O(n log n).