sort_heap() in C++

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.

  1. /*
  2.  * C++ Program to sort the heap using heap_sort() operation
  3.  */
  4. #include <iostream>
  5. #include <vector>
  6. #include <algorithm>
  7. #include <functional>
  8. #include <iomanip>
  9.  
  10. void print(const std::vector <int>& v)
  11. {
  12.     std::vector <int>::const_iterator i;
  13.     for(i = v.begin(); i != v.end(); i++)
  14.     {
  15.         std::cout << *i << " ";
  16.     }
  17.     std::cout << std::endl;
  18. }
  19.  
  20. int main()
  21. {
  22.     int arr[] = {10, 20, 40, 80, 160, 320};
  23.     std::vector<int> v(arr, arr + sizeof(arr) / sizeof(int));
  24.  
  25.     std::cout << "Vector" << std::setw(4) << ": ";
  26.     print(v);
  27.     // default make_heap creates max-heap
  28.     std::make_heap(v.begin(), v.end());
  29.     std::cout << "Heap" << std::setw(6) << ": ";
  30.     print(v);
  31.     sort_heap(v.begin(), v.end());
  32.     std::cout << "Sorted" << std::setw(4) << ": ";
  33.     print(v);
  34.     sort_heap(v.begin(), v.end(), std::greater<int>());
  35.     std::cout << "Reverse" << std::setw(3) << ": ";
  36.     print(v);
  37. }

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

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.