Printing heap vs printing array?

I'm writing 2 print functions for a heap class, but I'm having difficulty understanding the difference between these 2 functions

void displayHeap(ostream& out) const;
//prints the heap in level order
//Hint: level = floor(log2(i) + 1)

void displayArray(ostream& out) const;
//prints each element in the array (heap) separated by a comma

Any help is appreciated!
What is a "level order of heap"? You should know, for you are apparently studying heaps.

Is it: https://stackoverflow.com/questions/36385868/java-how-to-print-heap-stored-as-array-level-by-level
> but I'm having difficulty understanding the difference between these 2 functions

A binary heap is implemented as an array which stores the elements in level order.
There is no difference between the two except that when displayed level by level,
we would put a separator (say a new line) between each level.

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) ;
}

http://coliru.stacked-crooked.com/a/c0f0cb951bf5e3a3
Topic archived. No new replies allowed.