In this shot, we will discuss how to use the partial_sort()
function in C++. It is present in the
<algorithm>
library.
The partial_sort()
function is used for sorting a part of the range, not the entire range.
The partial_sort()
function takes the following parameters:
Begin
: This is a random access iterator pointing to the first element in the range.End
: This is a random access iterator pointing to the first element in the range.Boundary
: This is a random access iterator pointing to the upper boundary element in the range [Begin, End), that is used as the upper boundary for the elements to be sorted.Pred
: This is a user-defined function which returns true
if the 2 arguments passed are in order (it follows strict weak ordering).The partial_sort()
function doesn’t return anything.
Let’s see the code snippet below.
#include<iostream>#include<algorithm>#include<vector>using namespace std;bool pred(int x, int y){return (x<y);}int main(){vector<int> vect = { 12, 15, 9, 7, 84, 74 },v(4);vector<int>::iterator ip;partial_sort(vect.begin(), vect.begin() + 4, vect.end(), pred);cout<<"The resultant vector after using partial_sort() is: ";for (ip = vect.begin(); ip != vect.end(); ip++)cout << *ip << " ";cout<<endl;return 0;}
main
function.partial_sort()
method to sort a subrange of the entire initialized vector.partial_sort()
function on the vector.In this way, we can use the partial_sort()
function in C++.