A Guide to Sort Function in C++
Have you ever wondered how to organize data in C++ efficiently? The sort function in C++ comes to the rescue, offering a powerful and straightforward way to arrange elements in a sequence into a specified order. This function is part of the Standard Template Library (STL) and can be customized to sort arrays or vectors according to specific criteria, enhancing the performance and readability of your code. Let's 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.
Best-suited C++ courses for you
Learn C++ with these high-rated online courses
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
Thus, the std::sort function in C++ is a powerful tool for sorting elements in various data structures like arrays, vectors, and other containers.
FAQs
What is the sort function in C++?
The sort function in C++ is a standard library function that arranges the elements of a container (like an array or vector) in a specified order. It's part of the Standard Template Library (STL).
How do you use the sort function on an array?
To sort an array, you would include the <algorithm> header and use the sort function specifying the start and end pointers of the array: sort(arr, arr + n); where n is the number of elements in the array.
Can the sort function sort in descending order?
Yes, the sort function can sort elements in descending order by providing a third parameter as a comparison function or using the greater<int>() predefined function: sort(arr, arr + n, greater<int>());
Is it possible to sort a part of an array using the sort function?
es, you can sort a part of an array by specifying the starting and ending pointers of the subrange you want to sort: sort(arr + start, arr + end + 1);
How does the sort function compare elements by default?
By default, the sort function compares elements using the < operator, meaning it will arrange elements in ascending order based on their natural ordering.
Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio