This C++ program sorts the heap using sort_heap() operation. The default sort_heap operation sorts the elements of the heap in ascending order. The alternative version of sort_heap can sort the heap depending on the type of predicate and this alternative version takes predicate as its third parameter. The resulting range no longer has the heap property.

Here is the source code of the C++ program which sorts the heap using sort_heap() operation. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

`/*`

`* C++ Program to sort the heap using heap_sort() operation`

`*/`

`#include <iostream>`

`#include <vector>`

`#include <algorithm>`

`#include <functional>`

`#include <iomanip>`

void print(const std::vector <int>& v)

`{`

std::vector <int>::const_iterator i;

for(i = v.begin(); i != v.end(); i++)

`{`

std::cout << *i << " ";

`}`

std::cout << std::endl;

`}`

int main()

`{`

int arr[] = {10, 20, 40, 80, 160, 320};

std::vector<int> v(arr, arr + sizeof(arr) / sizeof(int));

std::cout << "Vector" << std::setw(4) << ": ";

print(v);

`// default make_heap creates max-heap`

std::make_heap(v.begin(), v.end());

std::cout << "Heap" << std::setw(6) << ": ";

print(v);

sort_heap(v.begin(), v.end());

std::cout << "Sorted" << std::setw(4) << ": ";

print(v);

sort_heap(v.begin(), v.end(), std::greater<int>());

std::cout << "Reverse" << std::setw(3) << ": ";

print(v);

`}`

$ a.out 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

**Sanfoundry Global Education & Learning Series – 1000 C++ Programs.**

If you wish to look at all C++ Programming examples, go to C++ Programs.