Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ algorithm::sort_heap function is used to sort elements in the heap range [first,last) into ascending order.

Syntax

//default version
template <class RandomAccessIterator>
  void sort_heap(
     RandomAccessIterator first, 
     RandomAccessIterator last
  );

//custom version 
template <class RandomAccessIterator, class Compare>
  void sort_heap(
     RandomAccessIterator first, 
     RandomAccessIterator last,
     BinaryPredicate comp
  );

Parameters

first Specify initial position of the random-access iterator. The range used is [first,last).
last Specify final position of the random-access iterator. The range used is [first,last).
comp A binary predicate that takes two elements in the range as arguments and returns a bool. It follows the strict weak ordering to order the elements.

Return Value

None.

Time Complexity

Up to linearithmic i.e, Θ(nlog(n)), where n is the distance between first and last.

Example:

In the below example, the algorithm::sort_heap function is used to rearrange the elements of a given vector to form a max heap.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
 
int main (){
  vector<int> vec{10, 5, 55, 22, 27, -10};
  vector<int>::iterator it;

  cout<<"vec contains:";
  for(it = vec.begin(); it != vec.end(); ++it)
    cout<<" "<<*it;

  //make the vector max heap
  make_heap(vec.begin(), vec.end());

  cout<<"\nAfter make_heap call, vec contains:";
  for(it = vec.begin(); it != vec.end(); ++it)
    cout<<" "<<*it;

  //sort the max heap
  sort_heap(vec.begin(), vec.end());

  cout<<"\nAfter sort_heap call, vec contains:";
  for(it = vec.begin(); it != vec.end(); ++it)
    cout<<" "<<*it;

  return 0;
}

The output of the above code will be:

vec contains: 10 5 55 22 27 -10
After make_heap call, vec contains: 55 27 10 22 5 -10
After sort_heap call, vec contains: -10 5 10 22 27 55

❮ C++ <algorithm> Library