 

Category: algorithms   Component type: function 
Prototype
Sort_heap
is an overloaded name; there are actually two sort_heap
functions.
template <class RandomAccessIterator>
void sort_heap(RandomAccessIterator first, RandomAccessIterator last);
template <class RandomAccessIterator, class StrictWeakOrdering>
void sort_heap(RandomAccessIterator first, RandomAccessIterator last,
StrictWeakOrdering comp);
Description
Sort_heap
turns a heap [1] [first, last)
into a sorted range. Note that this is not a stable sort: the relative order of equivalent elements is not guaranteed to be preserved.
The two versions of sort_heap
differ in how they define whether one element is less than another. The first version compares objects using operator<
, and the second compares objects using a functors comp
.
Definition
Defined in the standard header algorithm, and in the nonstandard backwardcompatibility header algo.h.
Requirements on types
For the first version, the one that takes two arguments:

RandomAccessIterator
is a model of RandomAccessIterator.

RandomAccessIterator
is mutable.

RandomAccessIterator
's value type is a model of LessThanComparable.

The ordering on objects of
RandomAccessIterator
's value type is a strict weak ordering, as defined in the LessThanComparable requirements.
For the second version, the one that takes three arguments:

RandomAccessIterator
is a model of RandomAccessIterator.

RandomAccessIterator
is mutable.

StrictWeakOrdering
is a model of StrictWeakOrdering.

RandomAccessIterator
's value type is convertible to StrictWeakOrdering
's argument type.
Preconditions
For the first version, the one that takes two arguments:

[first, last)
is a valid range.

[first, last)
is a heap. That is, is_heap(first, last)
is true
.
For the second version, the one that takes three arguments:

[first, last)
is a valid range.

[first, last)
is a heap. That is, is_heap(first, last, comp)
is true
.
Complexity
At most N * log(N)
comparisons, where N
is last  first
.
Example
int main()
{
int A[] = {1, 4, 2, 8, 5, 7};
const int N = sizeof(A) / sizeof(int);
make_heap(A, A+N);
copy(A, A+N, ostream_iterator<int>(cout, " "));
cout << endl;
sort_heap(A, A+N);
copy(A, A+N, ostream_iterator<int>(cout, " "));
cout << endl;
}
Notes
[1] A heap is a particular way of ordering the elements in a range of RandomAccessIterator [f, l)
. The reason heaps are useful (especially for sorting, or as priority queues) is that they satisfy two important properties. First, *f
is the largest element in the heap. Second, it is possible to add an element to a heap (using push_heap
), or to remove *f
, in logarithmic time. Internally, a heap is a tree represented as a sequential range. The tree is constructed so that that each node is less than or equal to its parent node.
See also
push_heap
, pop_heap
, make_heap
, is_heap
, sort
, stable_sort
, partial_sort
, partial_sort_copy