sort_heap()

The std::sort_heap() function is used to sort the heap in ascending order. It uses the heapsort algorithm and only works on the heap.

Below is the implementation of the above method:

C++




// C++ code to demonstrate the working of
// sort_heap()
#include <bits/stdc++.h>
using namespace std;
int main()
{
 
    // Initializing a vector
    vector<int> v1 = { 20, 30, 40, 25, 15 };
 
    // Converting vector into a heap
    // using make_heap()
    make_heap(v1.begin(), v1.end());
 
    // Displaying heap elements
    cout << "The heap elements are: ";
    for (int& x : v1)
        cout << x << " ";
    cout << endl;
 
    // sorting heap using sort_heap()
    sort_heap(v1.begin(), v1.end());
 
    // Displaying heap elements
    cout << "The heap elements after sorting are: ";
    for (int& x : v1)
        cout << x << " ";
 
    return 0;
}


Output

The heap elements are: 40 30 20 25 15 
The heap elements after sorting are: 15 20 25 30 40 

Complexity of the above method:

Time Complexity: O(NlogN), where N is the number of elements.

Heap in C++ STL

The heap data structure can be implemented in a range using STL which provides faster max or min item retrieval, and faster insertion and deletion on sorted data and also works as a sub-routine for heapsort.

Similar Reads

STL Functions for Heap Operations

make_heap(): Converts given range to a heap. push_heap(): Arrange the heap after insertion at the end. pop_heap(): Moves the max element at the end for deletion. sort_heap(): Sort the elements of the max_heap to ascending order. is_heap(): Checks if the given range is max_heap. is_heap_until(): Returns the largest sub-range that is max_heap....

1. make_heap() Function

The std::make_heap() function is used to convert the given range in a container to a heap. By default, it generates the max heap but we can use a custom comparator to change it to the min heap....

2. push_heap() Function

...

3. pop_heap() Function

The std::push_heap() function is used to sort the heap after the insertion of an element at the end of the heap. We use the push_back() function of std::vector class to insert a new element at the end of the vector then use the push_heap() function to place that element at its appropriate position....

4. sort_heap()

...

5. is_heap() Function

The std::pop_heap() function is used to move the largest element at the end of the heap so that we can safely remove the element without destroying the heap. Then we use the pop_back() function of std::vector class to actually remove that element....

6. is_heap_until() Function

...