Javatpoint Logo
Javatpoint Logo

C++ Algorithm sort_heap()

C++ Algorithm sort_heap() function is used to converts a heap [first, last) into a sorted range in ascending order.

Elements are compared using operator< for the first version or using the given binary comparison function comp for the second version.

Syntax

Parameter

first: A random access iterator pointing to the first element in the target heap.

last: A random access iterator pointing to the past last element in the target heap.

comp: A user defined binary predicate function that accepts two arguments and returns true if the two arguments are in order otherwise, it returns false. It follows the strict weak ordering to order the elements.

Return value

None

Complexity

Complexity is up to linearithmic in the distance between first and last: performs at most N*log (N) comparisons of elements and up to that many elements swaps or moves where N = last - first.

Data races

Some of the objects in the range [first, last) are modified.

Exceptions

This function throws an exception if any of element comparisons, the element swaps (or moves) or an operation on iterator throws an exception.

Note: The invalid parameters cause an undefined behavior.

Example 1

Let's see the simple example to demonstrate the use of sort_heap() using default version:

Output:

Here are the values in the heap:
11 22 36 17 3 25 1 2 7 
Now we sort these values into ascending order.
Here is the result:
1 2 3 7 17 22 25 36 11

Example 2

Let's see another simple example to demonstrate the use of sort_heap() using comparison function:

Output:

Here are the values in the heap:
11 12 15 17 13 100 36 19 0 
Now we sort these values into descending order.
Here are the results:
100 36 19 17 15 13 12 0 11  

Example 3

Let's see another simple example:

Output:

initial max heap   : 30
max heap after pop : 20
max heap after push: 99
final sorted range : 5 10 15 20 99

Example 4

Let's see a simple example:

Output:

Vector  : 10 20 40 80 160 320 
Heap    : 320 160 40 80 20 10 
Sorted  : 10 20 40 80 160 320 
Reverse : 320 160 80 40 20 10

Next TopicC++ Algorithm




Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA