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.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Next Steps:
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Buy Programming Books
- Buy Computer Science Books
- Apply for C++ Internship
- Practice Computer Science MCQs
- Buy C++ Books