In this guide, we will explore the variance between std::sort and std::stablesort in C++. Prior to delving into their distinctions, it is essential to understand the functionality of std::sort and std::stablesort, including their syntax, parameters, and illustrations.
What is the std::sort function in C++?
In C++ development, the std::sort function serves as a pre-existing function within the Standard Template Library (STL). Its primary purpose is to arrange the elements within the specified range [first, last] according to a specified order. This function provides a convenient and efficient method for organizing data in C++. Additionally, it offers the flexibility to enable custom sorting by defining a comparator function that outputs a Boolean value. The implementation of the std::sort function can be found in the <algorithm> header file of C++. Notably, this function is compatible only with data structures that support random access to their elements, such as vectors and arrays.
Syntax:
It has the following syntax:
template< class RandomIter>
void sort( RandomIter first, RandomIter last, comp );
Parameters:
- template< class RandomIter>: It is the template declaration.
- void sort( RandomIter first, RandomIter last, comp ): It is the function signature for the std::sort function template in C++. RandomIter first: It represents an iterator to the first element of the range that we want to sort. RandomIter last: It represents an iterator to the past last element of the range that we want to sort. Comp (optional): A binary function, lambda expression, or functor, that compares two elements in the range.
- RandomIter first: It represents an iterator to the first element of the range that we want to sort.
- RandomIter last: It represents an iterator to the past last element of the range that we want to sort.
- Comp (optional): A binary function, lambda expression, or functor, that compares two elements in the range.
Example:
Let's consider an instance to demonstrate the std::sort method in C++.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> Num{45, 37, 55, 22, 68, 19, 44};
// Sorting using std::sort
std::sort(Num.begin(), Num.end());
// Printing the sorted vector
for (const int& x: Num) {
std::cout << x<< " ";
}
}
Output:
19 22 37 44 45 55 68
What is the std::stable_sort function in C++?
The std::stablesort function is employed for arranging the elements within the range [first, last] in an ascending order. This function resembles the std::sort function, with the added capability of maintaining the original order of equivalent elements. The std::stablesort function is implemented in the C++’s algorithm header file.
Syntax:
It has the following syntax:
template< class RandomIter>
void stable_sort( RandomIter first, RandomIter last );
and the other syntax is:
template< class RandomIter, class Compare>
void stable_sort( RandomIter first, RandomIter last, Compare comp );
Parameters:
- template< class RandomIter>: It is the template declaration.
- void sort( RandomIter first, RandomIter last, comp ): It is the function signature for the std::stable_sort function template in C++. RandomIter first: It represents an iterator to the first element in the range. RandomIter last: It represents an iterator to the past last element in the range. Comp: It accepts two arguments and returns true if two inputs in order; otherwise, it returns false.
- RandomIter first: It represents an iterator to the first element in the range.
- RandomIter last: It represents an iterator to the past last element in the range.
- Comp: It accepts two arguments and returns true if two inputs in order; otherwise, it returns false.
Return Value:
It does not return any value.
Example:
Let's consider a scenario to demonstrate the functionality of the std::stable_sort method in the C++ programming language.
#include <algorithm>
#include <iostream>
#include <vector>
struct Employee {
std::string name;
int Department;
// Comparison operator for sorting by department
bool operator<(const Employee& other) const {
if (Department == other.Department) {
return name < other.name;
}
return Department < other.Department;
}
};
int main() {
std::vector<Employee> employees{
{"Alice", 2},
{"Grace", 2},
{"Charlie", 2},
{"David", 1},
{"Eve", 3},
{"Bob", 1},
{"Frank", 3}
};
// Sorting employees by department
std::stable_sort(employees.begin(), employees.end());
// Print the sorted employees
std::cout << "Sorted Employees:\n";
for (const Employee& emp : employees) {
std::cout << emp.name << " (Dept " << emp.Department << ")\n";
}
return 0;
}
Output:
Sorted Employees:
Bob (Dept 1)
David (Dept 1)
Alice (Dept 2)
Charlie (Dept 2)
Grace (Dept 2)
Eve (Dept 3)
Frank (Dept 3)
Key differences between std::sort and std::stable_sort function in C++:
There exist numerous fundamental variances between std::sort and std::stable_sort in C++. A few primary distinctions include:
| Features | Std::sort() | Std::stable_sort() |
|---|---|---|
| Stability | It is not stable, which means that there is no guarantee that the relative order of equivalent elements to be preserved. | It provides guarantees that it preserves the equivalent elements in their desired order. |
| Performance | It is usually faster than the std::stable_sort() because of fewer constraints. It uses several sort algorithms, including combining quicksort, heapsort, insertion sort, and an introspective sort algorithm. | It is slower than the std::sort() because of extra space allocation and stability overhead. |
| Use Cases | It is suitable when stability is not needed, and performance is required. | It is suitable when the stability is important. |
| Algorithm type | It mainly used a variation of the quicksort algorithm. | It mainly utilized a MergeSort-based algorithm. |
| Implementation Dependency | It mainly relies on the element comparison. | It mainly relies on element comparison but guarantees stable output. |
| Time Complexity | It has an O(n logn) average time complexity.Worst Case Complexity: O(n2) | It has O(n log2n) time complexity on the worst case. |
| Space Complexity | It requires O(1) additional space. | It requires O(n) additional space. |
Conclusion:
In summary, the std::sort and std::stable_sort functions play a crucial role in C++ programming. These functions are essential for arranging elements in a specific sequence. Recognizing the distinctions between these algorithms helps in selecting the most suitable option based on our needs. This process guarantees the accuracy and effectiveness of our software, enabling us to choose the optimal algorithm for our specific criteria.