Open In App
Related Articles

std::partial_sort in C++

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report
std::sort

is used for sorting the elements present within a container. One of the variants of this is

std::partial_sort

, which is used for sorting not the entire range, but only a sub-part of it. It rearranges the elements in the range [first, last), in such a way that the elements before middle are sorted in ascending order, whereas the elements after middle are left without any specific order. It can be used in two ways as shown below:

  1. Comparing elements using <: Syntax:
    Template 
    void partial_sort (RandomAccessIterator first, RandomAccessIterator middle,
                       RandomAccessIterator last);
    
    first: Random-Access iterator to the first element in the container.
    last: Random-Access iterator to the last element in the container.
    middle: Random-Access iterator pointing to the element in the 
    range [first, last), that is used as the upper boundary for the elements 
    to be sorted.
    
    Return Value: It has a void return type, so it does not return any value.
    
    

    CPP

    // C++ program to demonstrate the use of
    // std::partial_sort
    #include <iostream>
    #include <algorithm>
    #include <vector>
    using namespace std;
    int main()
    {
        vector<int> v = { 10, 45, 60, 78, 23, 21, 3 };
     
        vector<int>::iterator ip;
     
        // Using std::partial_sort
        std::partial_sort(v.begin(), v.begin() + 1, v.end());
     
        // Displaying the smallest element after applying
        // std::partial_sort
     
        ip = v.begin();
        cout << "The smallest element is = " << *ip;
     
        return 0;
    }
    
                        
    Output:
    1 1 3 10 3 3 7 7 8 
    
    
    Here, only first three elements are sorted from first to middle, and here first is v.begin() and middle is v.begin() + 3, and rest are without any order.
  2. By comparing using a pre-defined function: Syntax:
    Template
     void partial_sort (RandomAccessIterator first, RandomAccessIterator middle,
                        RandomAccessIterator last, Compare comp);
    
    Here, first, middle and last are the same as previous case.
    
    comp: Binary function that accepts two elements in the range 
    as arguments, and returns a value convertible to bool. The value 
    returned indicates whether the element passed as first 
    argument is considered to go before the second in the specific
    strict weak ordering it defines.
    The function shall not modify any of its arguments.
    This can either be a function pointer or a function object.
    
    Return Value: It has a void return type, so it does not return any value.
    
    

    CPP

    // C++ program to demonstrate the use of
    // std::partial_sort
    #include <iostream>
    #include <algorithm>
    #include <vector>
    using namespace std;
    int main()
    {
        vector<int> v = { 10, 45, 60, 78, 23, 21, 3 }, v1;
     
        int i;
        v1 = v;
        vector<int>::iterator ip;
     
        // Using std::partial_sort
        std::partial_sort(v.begin(), v.begin() + 2, v.end());
     
        // Using std::sort()
        std::sort(v1.begin(), v1.begin() + 2);
     
        cout << "v = ";
        for (i = 0; i < 2; ++i) {
            cout << v[i] << " ";
        }
     
        cout << "\nv1 = ";
        for (i = 0; i < 2; ++i) {
            cout << v1[i] << " ";
        }
     
        return 0;
    }
    
                        
    Output:
    1 1 3 10 3 3 7 7 8 
    
    

Where can it be used ?

  1. Finding the largest element: Since, with std::partial_sort, we can partially sort the container till whichever position we would like to. So, if we just sort the first position and use a function object , we can find the largest element, without having to sort the entire container.

    CPP

    
                        
    Output:
    The largest element is = 78
    
    
  2. Finding the smallest element: Similar to finding the largest element, we can also find the smallest element in the container in the previous example.

    CPP

    // C++ program to demonstrate the use of
    // std::partial_sort
    #include <iostream>
    #include <algorithm>
    #include <vector>
    using namespace std;
    int main()
    {
        vector<int> v = { 10, 45, 60, 78, 23, 21, 3 };
     
        vector<int>::iterator ip;
     
        // Using std::partial_sort
        std::partial_sort(v.begin(), v.begin() + 1, v.end());
     
        // Displaying the smallest element after applying
        // std::partial_sort
     
        ip = v.begin();
        cout << "The smallest element is = " << *ip;
     
        return 0;
    }
    
                        
    Output:
    The smallest element is = 3
    
    

Point to remember:

  • std::sort() vs std::partial_sort(): Some of you might think that why are we using std::partial_sort, in place we can use std::sort() for the limited range, but remember, if we use std::sort with a partial range, then only elements within that range will be considered for sorting, while all other elements outside the range will not be considered for this purpose, whereas with std::partial_sort(), all the elements will be considered for sorting.

    CPP

    // C++ program to demonstrate the use of
    // std::partial_sort
    #include <iostream>
    #include <algorithm>
    #include <vector>
    using namespace std;
    int main()
    {
        vector<int> v = { 10, 45, 60, 78, 23, 21, 3 }, v1;
     
        int i;
        v1 = v;
        vector<int>::iterator ip;
     
        // Using std::partial_sort
        std::partial_sort(v.begin(), v.begin() + 2, v.end());
     
        // Using std::sort()
        std::sort(v1.begin(), v1.begin() + 2);
     
        cout << "v = ";
        for (i = 0; i < 2; ++i) {
            cout << v[i] << " ";
        }
     
        cout << "\nv1 = ";
        for (i = 0; i < 2; ++i) {
            cout << v1[i] << " ";
        }
     
        return 0;
    }
    
                        
    Output:
    v = 3 10
    v1 = 10 45
    
    
    Explanation: Here, we applied std::partial_sort on v and std::sort on v1, upto second position. Now, you can understand that std::sort sorted only the element within the given range, whereas partial_sort took into consideration the whole container, but sorted only the first two positions.

The time complexity of std::partial_sort can be expressed as follows:

  • Average Case: O(n log k), where n is the number of elements in the range, and k is the number of elements to be partially sorted. Note that n log k is much smaller than n log n for k << n.
  • Worst Case: O(n log k). The worst-case time complexity is also n log k, where n is the number of elements and k is the number of elements to be partially sorted. However, this can be more costly than the average case when the range contains elements with expensive comparison operations.

The reason behind the time complexity of O(n log k) is that std::partial_sort internally uses a partial sorting algorithm based on a heap, such as the std::make_heap, std::pop_heap, and std::push_heap functions. These heap operations take logarithmic time complexity (O(log k)) to maintain the heap structure while processing k elements. The algorithm is applied to the entire range, resulting in the overall complexity of O(n log k) to partially sort the elements.

Keep in mind that std::partial_sort only guarantees that the k smallest (or largest) elements are in their sorted positions relative to each other, but not their absolute sorted order compared to the rest of the elements in the range. For a fully sorted range, you should use std::sort with a time complexity of O(n log n).


This article is contributed by

Mrigendra Singh

. If you like GeeksforGeeks and would like to contribute, you can also write an article using

or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.



Last Updated : 25 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads