Sorting algorithms/Heapsort: Difference between revisions

m
(added FunL)
Line 340:
 
=={{header|C++}}==
Uses C++11. Compile with
The easiest way is to use the <code>make_heap</code> and <code>sort_heap</code> standard library functions.
g++ -std=c++11 heap.cpp
<lang cpp>#include <iostream>
<lang cpp>#include <algorithm> // for std::make_heap, std::sort_heap
#include <iterator>
<lang cpp>#include <iostream>
template <typename Iterator>
 
void heapsort(Iterator begin, Iterator end)
template <typename IteratorRandomAccessIterator>
{
void heap_sort(RandomAccessIterator begin, RandomAccessIterator end) {
std::make_heap(begin, end);
std::sort_heapmake_heap(begin, end);
std::make_heapsort_heap(begin, end);
}
 
int main() {
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
{
heap_sort(std::begin(a), std::end(a));
double valsToSort[] = {
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
1.4, 50.2, 5.11, -1.55, 301.521, 0.3301, 40.17,
std::cout << "\n";
-18.0, 88.1, 30.44, -37.2, 3012.0, 49.2};
const int VSIZE = sizeof(valsToSort)/sizeof(*valsToSort);
 
heapsort(valsToSort, valsToSort+VSIZE);
for (int ix=0; ix<VSIZE; ix++) std::cout << valsToSort[ix] << std::endl;
return 0;
}</lang>
If you want to be slightly more verbose
<lang cpp>#include <iostream>
#include <algorithm> // for std::make_heap, std::pop_heap
template <typename Iterator>
void heapsort(Iterator begin, Iterator end)
{
std::make_heap(begin, end);
while (begin != end)
std::pop_heap(begin, end--);
}</lang>
Output:
<pre>
-199 -52 2 3 33 56 99 100 177 200
</pre>
 
=={{header|C sharp|C#}}==