News Leaflets
A leading news portal.

What’s the relationship between “a” heap and “the” heap?

0 14

#include <bits/stdc++.h>

using namespace std;

#define N 100

  

class Heap {

    int heap[N];

    int heapsize = -1;

    void Heapifyup()

    {

        int i = heapsize;

        while (i >= 0) {

            if (heap[i] <= heap[(i - 1) / 2]) {

                break;

            }

            else {

                swap(heap[i], heap[(i - 1) / 2]);

            }

            i = (i - 1) / 2;

        }

    }

    void Heapifydown()

    {

        int i = 0;

        while (i != heapsize) {

  

            if (heap[i]

                >= max(heap[2 * i + 1], heap[2 * i + 2])) {

                break;

            }

            else {

                int k;

                k = (heap[2 * i + 1] >= heap[2 * i + 2])

                        ? 2 * i + 1

                        : 2 * i + 2;

                swap(heap[i], heap[k]);

                i = k;

            }

        }

    }

  

public:

    void push(int val)

    {

        heapsize++;

        heap[heapsize] = val;

        Heapifyup();

        

    }

    void pop()

    {

        if (heapsize < 0) {

            cout << "Heap Underflow \n";

            return;

        }

        heap[0] = heap[heapsize];

        heapsize--;

        if (heapsize > 0) {

            Heapifydown();

            

        }

    }

    void print_heap()

    {

        for (int i = 0; i <= heapsize; i++) {

            cout << heap[i] << " ";

        }

        cout << endl;

    }

    int size() { return heapsize + 1; }

    int top()

    {

        if (heapsize < 0) {

            return -1;

        }

        return heap[0];

    }

};

  

int main(int argc, char const* argv[])

{

    Heap h;

    cout << h.top() << endl;

    cout << h.size() << endl;

    h.print_heap();

  

    h.pop();

    h.push(5);

    h.push(7);

    cout << h.top() << endl;

  

    h.push(6);

    h.push(4);

    h.print_heap();

    cout << h.size() << endl;

  

    h.pop();

    h.print_heap();

    cout << h.size() << endl;

  

    return 0;

}

FOLLOW US ON GOOGLE NEWS

Read original article here

Denial of responsibility! News Leaflets is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – [email protected]. The content will be deleted within 24 hours.

Leave a comment