
Have you ever wanted to bring order to chaos, just like how the sort function in C++ effortlessly arranges elements in a sequence? Let us understand more!
The Sort Function in C++ is a utility function provided by the C++ Standard Library to arrange elements in a range (like arrays or vectors) in a sorted order, either in ascending or descending order, based on specified criteria.
How is it useful?
- With just a single line of code, you can sort an entire collection of elements, which helps to keep your code concise and readable.
- Allows for easy customization through comparators, so you can define complex sorting criteria without making the code overly complex.
- The std::sort function is highly optimized, generally offering very good performance characteristics. It performs better than straightforward implementations of common sorting algorithms like bubble or insertion sort.
- The std::sort function integrates well with other parts of the C++ Standard Template Library (STL), allowing for powerful combinations of algorithms and data structures.
The Sort Function in C++ typically uses an efficient sorting algorithm called introsort, a hybrid sorting algorithm. Introsort combines quicksort, heapsort, and insertion sort elements to achieve good average-case and worst-case time complexity while maintaining performance across different scenarios.
By default, the sort function will sort the elements in ascending order.
Examples to Understand Sort Function in C++
Sorting in Ascending Order
#include <iostream>#include <algorithm> // Include the necessary header
int main() { int arr[] = {5, 4, 2, 1, 3}; int n = sizeof(arr) / sizeof(arr[0]);
// Using std::sort to sort the array in ascending order std::sort(arr, arr + n);
std::cout << "Sorted Array in Ascending Order: "; for (int i = 0; i < n; i++) { std::cout << arr[i] << " "; }
return 0;}
Output
Sorted Array in Ascending Order: 1 2 3 4 5
This demonstrates the default behaviour of std::sort() in C++, sorting elements in ascending order.
Sorting in Descending Order
#include <iostream>#include <algorithm>#include <vector>
int main() { std::vector<int> vec = {1, 5, 2, 4, 3};
// Using std::sort to sort the vector in descending order std::sort(vec.begin(), vec.end(), std::greater<int>());
std::cout << "Sorted Vector in Descending Order: "; for (int i : vec) { std::cout << i << " "; }
return 0;}
Output
Sorted Vector in Descending Order: 5 4 3 2 1
This demonstrates how to use std::greater<>() to sort elements in descending order with the std::sort() function in C++.
Sorting, in Particular Order
#include <iostream>#include <algorithm>#include <vector>
// Custom comparator functionbool customComparator(const std::string& name1, const std::string& name2) { // Sort names alphabetically in ascending order return name1 < name2;}
int main() { std::vector<std::string> names = {"Esha", "Hrithik", "Hroohee", "Hrahe", "Ehsas"};
// Using std::sort with the customComparator to sort names alphabetically in ascending order std::sort(names.begin(), names.end(), customComparator);
std::cout << "Sorted Names (Ascending Order): "; for (const std::string& name : names) { std::cout << name << " "; }
return 0;}
Output
Sorted Names (Ascending Order): Ehsas Esha Hrahe Hrithik Hroohee
You can define custom comparators to sort elements based on any specific criteria you need, such as alphabetical order, length, or any other custom comparison logic.
Miscellaneous Example of Sort Function in C++
In this example, we’ll create a vector of Person objects and sort them based on their ages:
#include <iostream>#include <algorithm>#include <vector>#include <string>
// Define a custom class for Personclass Person {public: std::string name; int age;
// Constructor Person(const std::string& n, int a) : name(n), age(a) {}
// Overload the less-than operator for custom comparison bool operator<(const Person& other) const { return age < other.age; }};
int main() { // Create a vector of Person objects std::vector<Person> people = { {"Esha", 30}, {"Hrithik", 19}, {"Isha", 7}, {"Gauri", 10}, {"Ishani", 34} };
// Sort the vector of Person objects based on age std::sort(people.begin(), people.end());
// Print the sorted list of people std::cout << "Sorted People by Age:\n"; for (const Person& person : people) { std::cout << "Name: " << person.name << ", Age: " << person.age << "\n"; }
return 0;}
Output
Sorted People by Age: Name: Isha, Age: 7 Name: Gauri, Age: 10 Name: Hrithik, Age: 19 Name: Esha, Age: 30 Name: Ishani, Age: 34
Conclusion
Thus, the std::sort function in C++ is a powerful tool for sorting elements in various data structures like arrays, vectors, and other containers.
Download this article as PDF to read offline
Download as PDF
I'm Esha Gupta, a B.Tech graduate in Computer Science & Engineering, specializing in Front End Web Dev. I've interned at GeeksforGeeks & Coding Minutes, fueling my passion for crafting appealing and functional digit... Read Full Bio
Comments