Sort in C++ STL
About Sorting in STL
The C++ Standard Template Library (STL) is a powerful collection of template classes and functions that offer generic algorithms to manipulate data containers effortlessly. STL includes several efficient sorting algorithms, making it a popular choice among C++ programmers.Sorting Algorithms in C++ STL
- std::sort()
- std::stable_sort()
- std::partial_sort()
- std::nth_element()
- std::make_heap() and std::sort_heap()
Syntax of Sort() :
sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
The function doesn’t produce a result. Just the items/elements from the first to the last iterations are updated. The third parameter, comp, must be a function that establishes the hierarchy of the components to be sorted in. If nothing else is supplied, the sorting happens in ascending order.
Example of Sorting in Ascending Order :
#include<iostream> #include<bits/stdc++.h> using namespace std; int main() { vectorarr; arr.push_back(34); arr.push_back(70); arr.push_back(20); arr.push_back(56); arr.push_back(1); cout<<"The element of array before sorting : "; for(int i=0;i < arr.size();i++){ cout<< arr[i]<<" "; } cout<< endl; // sort function to sorting the elements sort(arr.begin(), arr.end()); cout<<"The element of array after sorting : "; for(int i=0;i < arr.size();i++){ cout<< arr[i]<<" "; } return 0; }
Output :
The element of array before sorting : 34 70 20 56 1 The element of array after sorting : 1 20 34 56 70
In the above program, we take the array and used sort function to sort the elements in ascending order as comparator is not used , by default elements are arranged in ascending order.
Example of Sorting in Descending Order:
#include<iostream> #include<bits/stdc++.h> using namespace std; int main() { vectorarr; arr.push_back(34); arr.push_back(70); arr.push_back(20); arr.push_back(56); arr.push_back(1); cout<<"The element of array before sorting : "; for(int i=0;i< arr.size();i++){ cout<< arr[i]<<" "; } cout< ()); cout<<"The element of array after sorting : "; for(int i=0;i< arr.size();i++){ cout<< arr[i]<<" "; } return 0; }
Output :
The element of array before sorting : 34 70 20 56 1 The element of array after sorting : 70 56 34 20 1
In the above program, we take the array and used sort function to sort the elements in decreasing order as greater<int>() comparator is used to sort the elements in decreasing order
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment