Published: 26 Nov 2025 | Reading Time: 5 min read
"Data is only useful when it's organized, sorting is how C++ turns chaos into clarity."
Sorting silently drives nearly every application you use, whether it's for algorithm optimization, search result filtering, or score ranking.
Sorting is an essential skill for anybody learning or developing C++; it is a superpower. It enables you to create code more quickly, ace coding interviews, and comprehend the inner workings of complicated systems. From simple arrays to custom objects, sorting decides how efficiently your program performs.
In this blog, you'll explore everything from the lightning-fast std::sort() to custom comparators, lambda sorting, and real-world sorting algorithms like Bubble Sort, Merge Sort, and more, with clear explanations and clean C++ examples. By the end, you'll know exactly how to sort anything in C++, the smart, modern way.
The std::sort() function in C++ is a powerful and efficient sorting tool provided by the Standard Template Library (STL). It is based on Introsort, a hybrid sorting algorithm that switches between Quick Sort, Heap Sort, and Insertion Sort to achieve optimal performance. This makes std::sort() one of the fastest and most commonly used ways to sort in C++.
// Default sorting (Ascending order)
void sort(RandomAccessIterator first, RandomAccessIterator last);
// Sorting with a custom comparator function
void sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp);
The std::sort function in C++ is a function template designed for maximum flexibility and efficiency. To use the sort function properly, one must be familiar with the parameters it takes and the information it returns for a number of different situations.
std::sort has two main forms:
// Default sorting (ascending order)
void sort(RandomAccessIterator first, RandomAccessIterator last);
// Sorting with a custom comparator
void sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp);
The comparator must enforce a strict weak ordering. It should accept two arguments and return true if the first should go before the second.
Examples:
bool compare(int a, int b)
{
return a > b;
}
std::sort(arr, arr + n, compare);
struct {
bool operator()(const std::pair<int, int>& a, const std::pair<int, int>& b) const {
return a.second < b.second; // sort by second element
}
} sortbysec;
std::sort(vec.begin(), vec.end(), sortbysec);
std::sort(vec.begin(), vec.end(),
[](int a, int b) {
return a > b; // sort in descending order
});
With C++17 and later, you can use an execution policy as the first argument to enable parallel sorting:
#include <execution>
std::sort(std::execution::par,
vec.begin(),
vec.end());
std::sort does not return a value. It sorts the elements in-place, directly modifying the provided range.
After calling std::sort, the elements in the specified range are reordered according to the chosen comparator. No new container or array is created—the original data is sorted in place. Always check that your comparator is correct and that your iterators define a valid range to avoid undefined behavior.
| Parameter | Description |
|---|---|
| first | Start of range (iterator or pointer) |
| last | End of range (iterator or pointer, one past last element) |
| comp (optional) | Comparator (function, pointer, functor, or lambda) |
| execution policy (C++17+) | Parallelization control (std::execution::par) |
Knowing what parameters std::sort accepts and what it returns lets you sort any data type with custom logic, in-place, and even in parallel for modern C++.
Arrays are one of the most commonly used data structures in C++ for storing multiple elements of the same type. Sorting an array is an important operation that helps in searching, organizing, and optimizing data processing. The C++ sort function from the Standard Template Library (STL) efficiently sorts arrays in ascending or descending order with minimal effort.
#include <iostream>
#include <algorithm> // For std::sort()
int main() {
int arr[] = {8, 3, 7, 1, 9, 5};
int n = sizeof(arr) / sizeof(arr[0]); // Calculate array size
std::sort(arr, arr + n); // Sort array in ascending order
std::cout << "Sorted array: ";
for (int i = 0; i < n; ++i) {
std::cout << arr[i] << " "; // Print sorted elements
}
std::cout << std::endl;
return 0;
}
It declares an integer array with items that are not sorted. The array's element count may be found with the help of the sizeof operator. The array is then automatically sorted in ascending order using the C++ sort function. Using Sort in C++, we can efficiently arrange the elements as needed.
After sorting, we use a for loop to iterate through the sorted array and print each element. Compared to simple sorting methods like Bubble Sort or Insertion Sort, std::sort() dramatically lowers the time complexity since it is an efficient sorting algorithm.
Sorted array: 1 3 5 7 8 9
When an array is sorted descendingly, its elements are arranged from greatest to smallest. Custom sorting measures may be defined using comparison functions with the help of the C++ sort function. We may use std::greater(), which verifies that bigger values appear before smaller ones, to sort an array in descending order.
#include <iostream>
#include <algorithm> // For std::sort() and std::greater<int>()
int main() {
int arr[] = {7, 2, 9, 5, 1, 6};
int n = sizeof(arr) / sizeof(arr[0]); // Calculate array size
std::sort(arr, arr + n, std::greater<int>()); // Sort in descending order
std::cout << "Sorted array in descending order: ";
for (int i = 0; i < n; ++i) {
std::cout << arr[i] << " "; // Print sorted elements
}
std::cout << std::endl;
return 0;
}
In this program, we declare an integer array with unsorted values. The C++ sort function is then used with std::greater(), which confirms that elements are arranged in descending order. The sorting modifies the array in place.
We will loop through the array's items and output them on the screen in decreasing order after sorting the array's numbers. This is a very efficient way of ordering an array for purposes of ranking information, including score rankings, task prioritization, and arranging information from highest to lowest.
Sorted array in descending order: 9 7 6 5 2 1
Vectors are dynamic arrays in C++ that can grow or shrink in size as needed. Unlike regular arrays, vectors have more flexibility and are highly used in modern programming. Sort in C++ is an essential operation, and vector sort is similar to sorting an array. An effective method for doing this is to use the Standard Template Library's (STL) sort function.
#include <vector>
#include <iostream>
#include <algorithm> // For std::sort()
int main() {
std::vector<int> vec = {7, 2, 9, 1, 5};
std::sort(vec.begin(), vec.end()); // Sort vector in ascending order
std::cout << "Sorted vector: ";
for (int num : vec) {
std::cout << num << " "; // Print sorted elements
}
std::cout << std::endl;
return 0;
}
Here, we declare a vector containing unsorted values. The C++ sort function takes two arguments: vec.begin() (starting position) and vec.end() (ending position) to sort the elements in ascending order. Since C++ vector sort uses dynamic memory, sorting is performed efficiently without needing manual size calculations.
Following sorting, the sorted items are shown by iterating through the vector using a range-based for loop. Because C++ vector sort has built-in methods like push_back() and size() and automatically handles memory allocation, it is superior to arrays.
Sorted vector: 1 2 5 7 9
Vectors are dynamic arrays in C++ that allow easy manipulation of elements. Sorting a vector in descending order is useful when arranging data from largest to smallest. The C++ sort function, combined with the std::greater() comparator, is commonly used to sort in C++ efficiently.
#include <iostream>
#include <algorithm>
#include <vector> // Include vector library
int main() {
std::vector<int> vec = {7, 2, 9, 1, 5}; // Unsorted vector
std::sort(vec.begin(), vec.end(), std::greater<int>()); // Sort in descending order
std::cout << "Sorted vector in descending order: ";
for (int num : vec) {
std::cout << num << " "; // Print sorted vector
}
std::cout << std::endl;
return 0;
}
We define a C++ vector sort containing unsorted elements. The sort function in C++ is used with std::greater() as a comparator so that elements are arranged in descending order. The sorting modifies the vector in place.
We then use a range-based for loop to iterate through the sorted vector and print the elements. This approach provides an efficient way to sort and display data while maintaining code simplicity and readability.
Sorted vector in descending order: 9 7 5 2 1
One of the most powerful features of a sort in C++ is its ability to use custom comparison functions. This allows sorting elements based on specific criteria rather than just in ascending order. We can sort elements in descending order by defining a custom comparison function, based on absolute values, string lengths, or any other condition.
Lambda expressions provide a compact and efficient way to define comparison functions directly within the sort function C++. Here is an example showing how to sort a vector in descending order using a lambda function:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> vec = {7, 2, 9, 4, 6};
// Sorting in descending order using a lambda function
std::sort(vec.begin(), vec.end(), [](int a, int b) {
return a > b; // Custom comparison: sort in descending order
});
std::cout << "Sorted vector in descending order: ";
for (int i : vec) {
std::cout << i << " "; // Print sorted elements
}
std::cout << std::endl;
return 0;
}
In this program, we use a std::vector to store a set of integers. Instead of the default ascending order, we pass a lambda function to the sort function C++ as a third argument. This lambda function takes two parameters (a and b) and returns true if a is greater than b.
After sorting, we use a for loop to iterate through the C++ vector sort and print each element. Since the sorting modifies the original vector, no additional space is required for sorting.
Sorted vector in descending order: 9 7 6 4 2
In C++, a functor (function object) is a class or struct that overloads the operator(), which allows objects of that class to be called like functions. Functors are useful for implementing custom comparison logic when sorting data. Unlike regular functions or lambda expressions, functors maintain state and can be reused efficiently.
#include <iostream>
#include <algorithm>
#include <vector>
struct CustomCompare {
bool operator()(int a, int b) const {
return a > b; // Sort in descending order
}
};
int main() {
std::vector<int> vec = {7, 1, 9, 3, 5};
std::sort(vec.begin(), vec.end(), CustomCompare()); // Use functor for sorting
std::cout << "Sorted vector in descending order: ";
for (int i : vec) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
In this program, we define a struct CustomCompare that overloads the operator(). This functor returns true when the first argument is greater than the second. We then use the sort function C++ with CustomCompare() as the third argument to apply our custom comparison logic.
The C++ vector sort is then printed, displaying the elements in descending order. Using functors allows for more flexible and reusable comparison logic, which is useful for complex sorting operations.
Sorted vector in descending order: 9 7 5 3 1
C++ lets you build custom function objects, called functors, to control sorting behavior in addition to standard lambdas and comparator functions. Classes or structs known as functors overload operator(), enabling you to contain intricate comparison logic and even save internal information.
#include <iostream>
#include <algorithm>
#include <vector>
struct ModuloCompare {
int mod;
ModuloCompare(int m) : mod(m) {}
bool operator()(int a, int b) const {
return (a % mod) < (b % mod); // compare by modulo value
}
};
int main() {
std::vector<int> vec = {13, 7, 2, 19, 5, 11};
std::sort(vec.begin(), vec.end(), ModuloCompare(5)); // Sort by value modulo 5
for (int n : vec)
std::cout << n << " ";
std::cout << std::endl;
return 0;
}
5 7 2 11 13 19 (sorted by n % 5)
Functors are especially helpful when the comparison logic is reused or needs configuration, such as sorting by a dynamic parameter.
For large datasets, sorting can become a performance bottleneck. Modern C++ (since C++17) introduces parallel execution policies that allow you to take advantage of multi-core processors with minimal code changes.
The standard library will try to parallelize the sorting process by dividing the work across many threads when std::execution::par is passed as the first parameter to std::sort.
#include <iostream>
#include <algorithm>
#include <vector>
#include <execution> // Required for execution policies
int main() {
std::vector<int> data = {15, 3, 9, 8, 5, 2, 7, 1, 6, 4};
std::sort(std::execution::par, data.begin(), data.end()); // Parallel sort
for (int n : data)
std::cout << n << " ";
std::cout << std::endl;
return 0;
}
1 2 3 4 5 6 7 8 9 15
When working with user-defined data types in C++, sorting objects of a class is required. Since std::sort() works with fundamental data types by default, we need to specify how objects should be compared. This can be achieved by overloading the < operator inside the class or by providing a custom comparison function. When implementing a Sort in C++ for such objects, providing a well-defined comparison mechanism is essential for correct ordering.
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
class Person {
public:
std::string name;
int age;
// Constructor to initialize name and age
Person(const std::string& n, int a) : name(n), age(a) {}
// Overloading the < operator for sorting based on age
bool operator<(const Person& other) const {
return age < other.age;
}
};
int main() {
std::vector<Person> people = {
{"Aarav", 25},
{"Meera", 18},
{"Vikram", 40},
{"Sanya", 30},
{"Kabir", 22}
};
std::sort(people.begin(), people.end()); // Sorts based on the overloaded < operator
std::cout << "Sorted people by age:\n";
for (const Person& person : people) {
std::cout << "Name: " << person.name << ", Age: " << person.age << "\n";
}
return 0;
}
In this code, we define a Person class with name and age attributes. The constructor initializes these values. To enable sorting, we overload the < operator so that objects are compared based on the age attribute.
The std::sort() function then uses this operator to sort function C++ the vector of Person objects. After sorting, a loop iterates through the vector and prints the sorted objects. Since the < operator is overloaded to compare ages, the sorting happens in ascending order of age.
Sorted people by age:
Name: Meera, Age: 18
Name: Kabir, Age: 22
Name: Aarav, Age: 25
Name: Sanya, Age: 30
Name: Vikram, Age: 40
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
// Define a Person class
class Person {
public:
std::string name;
int age;
Person(const std::string& n, int a) : name(n), age(a) {} // Constructor
};
// Custom comparator for sorting people by age
struct ComparePeople {
bool operator()(const Person& a, const Person& b) const {
return a.age < b.age; // Sort in ascending order of age
}
};
int main() {
// Create a list of people
std::vector<Person> people = {
{"Esha", 30},
{"Hrithik", 19},
{"Isha", 7},
{"Gauri", 10},
{"Ishani", 34}
};
// Sort the list using custom comparator
std::sort(people.begin(), people.end(), ComparePeople());
// Display sorted people
std::cout << "Sorted people by age:\n";
for (const Person& person : people) {
std::cout << "Name: " << person.name << ", Age: " << person.age << "\n";
}
return 0;
}
A constructor is used to initialize these attributes when objects are created. The ComparePeople structure is then defined, which contains a custom comparison function to sort Person objects by age in ascending order.
The std::sort() function is used with the custom comparator ComparePeople(). Finally, a loop prints the sorted list of people that displays their names and ages in ascending order.
Sorted people by age:
Name: Isha, Age: 7
Name: Gauri, Age: 10
Name: Hrithik, Age: 19
Name: Esha, Age: 30
Name: Ishani, Age: 34
Except for using the built-in std::sort() function, C++ allows programmers to implement custom sorting algorithms. These algorithms help in understanding how sorting works at a more in-depth level and can be optimized for specific use cases. When learning how to sort in C++, exploring different sorting techniques can provide valuable insights into algorithm efficiency and design.
When nearby items are in the incorrect order, the Bubble Sort algorithm continually compares them and switches them.
#include <iostream>
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; ++i) {
for (int j = 0; j < n - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
std::swap(arr[j], arr[j + 1]); // Swap if elements are in the wrong order
}
}
}
}
int main() {
int arr[] = {6, 2, 8, 4, 10, 1};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n); // Call Bubble Sort function
std::cout << "Sorted array: ";
for (int i = 0; i < n; ++i) {
std::cout << arr[i] << " "; // Print sorted array
}
std::cout << std::endl;
return 0;
}
We define the bubbleSort() function, which takes an array and its size as arguments. The algorithm iterates through the array multiple times, comparing adjacent elements and swapping them if needed. With each iteration, the largest unsorted element moves to its correct position at the end.
The process continues until the array is completely sorted. The main function initializes an unsorted array, calls bubbleSort(), and then prints the sorted result. However, Bubble Sort is easy to implement.
Sorted array: 1 2 4 6 8 10
Insertion Sort is a basic yet efficient sorting algorithm which functions similarly to how we arrange playing cards in our hands. By selecting each element and positioning it correctly among the previously sorted items, it constructs the sorted array one element at a time.
#include <iostream>
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; ++i) {
int key = arr[i]; // Store the current element
int j = i - 1;
// Shift elements of the sorted part to make space for key
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key; // Insert key at its correct position
}
}
int main() {
int arr[] = {9, 5, 1, 4, 3};
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
std::cout << "Sorted array: ";
for (int i = 0; i < n; ++i) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return 0;
}
In this program, we define a function insertionSort() that sorts an array using the Insertion Sort algorithm. It starts by assuming the first element is already sorted and then iterates through the rest of the array. Each new element (key) is compared with the sorted part, and elements are shifted to make space for inserting the key at its correct position.
The algorithm uses a nested loop: the outer loop picks elements one by one, while the inner loop shifts elements in the sorted section until the correct position for the key is found. This guarantees that the left portion of the array stays sorted following each iteration.
Sorted array: 1 3 4 5 9
The divide and conquer strategy is the basis for the sorting algorithm known as Merge Sort. It splits the array into smaller subarrays, sorts them, and then merges them back together in a sorted order. This technique guarantees a worst-case time complexity with O(n log n) and is effective for huge datasets.
#include <iostream>
// Function to merge two sorted subarrays
void merge(int arr[], int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int leftArr[n1], rightArr[n2];
// Copy elements to temporary arrays
for (int i = 0; i < n1; i++)
leftArr[i] = arr[left + i];
for (int i = 0; i < n2; i++)
rightArr[i] = arr[mid + 1 + i];
int i = 0, j = 0, k = left;
// Merge the temporary arrays back into the original array
while (i < n1 && j < n2) {
if (leftArr[i] <= rightArr[j])
arr[k++] = leftArr[i++];
else
arr[k++] = rightArr[j++];
}
// Copy remaining elements, if any
while (i < n1)
arr[k++] = leftArr[i++];
while (j < n2)
arr[k++] = rightArr[j++];
}
// Recursive Merge Sort function
void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
// Driver function
int main() {
int arr[] = {8, 3, 7, 1, 9, 5};
int n = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, n - 1);
std::cout << "Sorted array: ";
for (int i = 0; i < n; ++i) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return 0;
}
Here in this code splits an array in half, sorts each half separately, and then merges the two halves using a recursive approach called Merge Sort. The mergeSort() function divides the array repeatedly until single-element subarrays are created. The merge() technique is then used to rebuild these sorted subarrays in sorted order.
When the items are combined back, they are kept in separate temporary arrays called leftArr and rightArr until ready to combine into one sorted array. This merging process guarantees that the individual pieces of an object's proper place within the full structure are precisely merged together after sorting has occurred. Hence, a consistent and efficient way of sorting is through the above.
Sorted array: 1 3 5 7 8 9
With its hybrid Introsort engine, std::sort() makes sorting in C++ both strong and efficient. C++ offers a variety of methods for sorting data, including built-in functions, lambdas, functors, and traditional algorithms like Bubble Sort, Insertion Sort, and Merge Sort, regardless of whether you're working with arrays, vectors, or custom objects. Gaining an understanding of the aforementioned strategies can help you perform better, gain a firm grasp of software development and programming interview requirements, and increase your knowledge of data structures.
The std::sort() function is an STL utility that rearranges elements in a given range. It can sort data in ascending, descending, or any custom order depending on the comparator you provide.
Include the header and call:
std::sort(arr, arr + n);
Here, arr is the starting address and arr + n points just past the last element.
Yes. To sort in descending order, pass std::greater() as the comparator:
std::sort(arr, arr + n, std::greater<int>());
Absolutely. You can sort only a specific segment by defining a subrange:
std::sort(arr + start, arr + end + 1);
Only the elements within that range will be rearranged.
By default, std::sort() uses the < operator to compare values, which results in ascending order.
std::sort() uses Introsort, a hybrid algorithm that combines Quick Sort, Heap Sort, and Insertion Sort to ensure both speed and worst-case reliability.
Use the same function as arrays:
std::sort(vec.begin(), vec.end());
This sorts all elements between the beginning and end iterators in ascending order.
Source: NxtWave - https://www.ccbp.in/blog/articles/sort-in-cpp