![]() |
VOOZH | about |
Sorting a vector in C++ means arranging its elements in a specific order such as ascending, descending, or user-defined order. The C++ STL provides efficient sorting functions and comparators to sort vectors easily.
The STL provides different sorting methods to arrange vector elements in ascending, descending, custom, or stable order.
The sort() function from the <algorithm> header file is used to sort elements in ascending order by default. It has a time complexity of O(n log n) and a space complexity of O(1).
1 2 3 4 5
Explanation
In this program, the sort() function rearranges the vector elements in ascending order.
C++ provides a built-in comparator greater<int>() that can be passed to sort() to arrange elements in descending order. It has a time complexity of O(n log n) and a space complexity of O(1).
5 4 3 2 1
Explanation
In this program, the sort() function uses the greater<int>() comparator to sort the vector in descending order.
A custom comparator in C++ is a user-defined function or callable object that specifies how two elements should be compared during sorting. It allows sorting elements in a custom order instead of the default ascending order used by sort(). The sorting operation has a time complexity of O(n log n) and a space complexity of O(1).
5 4 3 2 1
Explanation
In this program, the sort() function uses the custom comparator comp() to determine the order of elements.
The stable_sort() function from the <algorithm> header file is similar to sort(), but it preserves the relative order of equal elements after sorting. It has a time complexity of O(n log n) and a space complexity of O(n).
1 2 3 4 5
Explanation
In this program, the stable_sort() function sorts the vector elements in ascending order.