C++ <algorithm> - sort() Function
The C++ algorithm::sort function is used to sort the elements in the range [first,last) into increasing order. The elements are compared using operator< (in first version) or comp (in second version). Equivalent elements are not guaranteed to preserve their original relative order.
Syntax
//default version template <class RandomAccessIterator> void sort (RandomAccessIterator first, RandomAccessIterator last); //custom version template <class RandomAccessIterator, class Compare> void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
Parameters
first |
Specify initial position of the random-access iterator of the sequence to be sorted. The range used is [first,last). |
last |
Specify final position of the random-access iterator of the sequence to be sorted. The range used is [first,last). |
comp |
Specify a binary function that accepts two element as arguments, and returns a value convertible to bool. The returned value indicates whether the first argument is considered to go before the second using the strict weak ordering it defines. |
Return Value
None.
Time Complexity
On Average, Linearithmic i.e, Θ(nlog(n)).
Example:
In the example below, the algorithm::sort function is used to sort the given vector.
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main (){ vector<int> Vec= {10, 60, 50, 30, 40, 20}; cout<<"Vec contains: \n"; for(int i = 0; i < Vec.size(); i++) cout<<Vec[i]<<" "; //sorting the vector sort(Vec.begin(), Vec.end()); cout<<"\n\n"; cout<<"Sorted Vec contains: \n"; for(int i = 0; i < Vec.size(); i++) cout<<Vec[i]<<" "; return 0; }
The output of the above code will be:
Vec contains: 10 60 50 30 40 20 Sorted Vec contains: 10 20 30 40 50 60
Example:
The example below shows how to use comp with algorithm::sort function to sort the vector in decreasing order.
#include <iostream> #include <algorithm> #include <vector> using namespace std; bool greater_than (int i, int j) { return (i>j); } int main (){ vector<int> Vec= {10, 60, 50, 30, 40, 20}; cout<<"Vec contains: \n"; for(int i = 0; i < Vec.size(); i++) cout<<Vec[i]<<" "; //sorting the vector sort(Vec.begin(), Vec.end(), greater_than); cout<<"\n\n"; cout<<"Sorted Vec contains: \n"; for(int i = 0; i < Vec.size(); i++) cout<<Vec[i]<<" "; return 0; }
The output of the above code will be:
Vec contains: 10 60 50 30 40 20 Sorted Vec contains: 60 50 40 30 20 10
❮ C++ <algorithm> Library