1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
#include <iostream>
#include <vector>
#include <algorithm>
template < typename SEQ >
void print_heap_level_by_level( const SEQ& heap, std::ostream& stm = std::cout )
{
std::size_t level_number = 0 ; // zero is the top most level
std::size_t num_items_at_this_level = 1 ; // level zero has at most one item
std::size_t num_printed_this_level = 0 ; // number of items printed at this level
for( const auto& v : heap ) // for each item in the heap
{
if( num_printed_this_level == 0 ) // start of a new level
stm << "\nlevel #" << level_number << " : " ;
stm << v << ' ' ;
++num_printed_this_level ;
if( num_printed_this_level == num_items_at_this_level ) // completed this level
{
++level_number ;
num_items_at_this_level *= 2 ; // next level has at most twice as many items
num_printed_this_level = 0 ;
}
}
stm << '\n' ;
}
int main()
{
std::vector<int> heap { 22, 67, 32, 56, 88, 99, 12, 56, 32, 45, 86, 64, 71,
38, 41, 55, 62, 77, 19, 42, 71, 17, 53, 49 } ;
std::make_heap( std::begin(heap), std::end(heap) ) ;
// print heap as an array
for( int v : heap ) std::cout << v << ' ' ;
std::cout << '\n' ;
print_heap_level_by_level(heap) ;
}
|