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

• Last Updated : 24 Mar, 2023

A Heap:

A Heap” refers to the heap data structure where we can store data in a specific order. Heap is a Tree-based data structure where the tree is a complete binary tree.

Heap is basically of two types:

• Max-Heap: The key at the Root node of the tree will be the greatest among all the keys present in that heap and the same property will be followed by every sub-tree.
• Min-Heap: The key at the Root node of the tree will be the smallest among all the keys present in that heap and the same property will be followed by every sub-tree.

Heap representation

Implementation:

Below is the implementation of the Max-Heap Data Structure

C++

 `#include ``using` `namespace` `std;``#define N 100`` ` `// Heap Structure..``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();``        ``// heapify bottom up``    ``}``    ``void` `pop()``    ``{``        ``if` `(heapsize < 0) {``            ``cout << ``"Heap Underflow \n"``;``            ``return``;``        ``}``        ``heap[0] = heap[heapsize];``        ``heapsize--;``        ``if` `(heapsize > 0) {``            ``Heapifydown();``            ``// heapify top down``        ``}``    ``}``    ``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];``    ``}``};`` ` `// Driver code``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;``}`

Java

 `// Java Code for the above approach`` ` `import` `java.io.*;`` ` `// Heap Structure..``class` `Heap {``    ``int``[] heap = ``new` `int``[``100``];``    ``int` `heapsize = -``1``;``    ``void` `Heapifyup()``    ``{``        ``int` `i = heapsize;``        ``while` `(i >= ``0``) {``            ``if` `(heap[i] <= heap[(i - ``1``) / ``2``]) {``                ``break``;``            ``}``            ``else` `{``                ``int` `temp = heap[i];``                ``heap[i] = heap[(i - ``1``) / ``2``];``                ``heap[(i - ``1``) / ``2``] = temp;``            ``}``            ``i = (i - ``1``) / ``2``;``        ``}``    ``}``    ``void` `Heapifydown()``    ``{``        ``int` `i = ``0``;``        ``while` `(i != heapsize) {``            ``if` `(heap[i] >= Math.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``);``                ``int` `temp = heap[i];``                ``heap[i] = heap[k];``                ``heap[k] = temp;``                ``i = k;``            ``}``        ``}``    ``}``    ``void` `push(``int` `val)``    ``{``        ``heapsize++;``        ``heap[heapsize] = val;``        ``Heapifyup();``        ``// heapify bottom up``    ``}``    ``void` `pop()``    ``{``        ``if` `(heapsize < ``0``) {``            ``System.out.println(``"Heap Underflow "``);``            ``return``;``        ``}``        ``heap[``0``] = heap[heapsize];``        ``heapsize--;``        ``if` `(heapsize > ``0``) {``            ``Heapifydown();``            ``// heapify top down``        ``}``    ``}``    ``void` `print_heap()``    ``{``        ``for` `(``int` `i = ``0``; i <= heapsize; i++) {``            ``System.out.print(heap[i] + ``" "``);``        ``}``        ``System.out.println();``    ``}``    ``int` `size() { ``return` `heapsize + ``1``; }``    ``int` `top()``    ``{``        ``if` `(heapsize < ``0``) {``            ``return` `-``1``;``        ``}``        ``return` `heap[``0``];``    ``}``}`` ` `class` `GFG {``    ``public` `static` `void` `main(String[] args)``    ``{``        ``Heap h = ``new` `Heap();``        ``System.out.println(h.top());``        ``System.out.println(h.size());``        ``h.print_heap();`` ` `        ``h.pop();``        ``h.push(``5``);``        ``h.push(``7``);``        ``System.out.println(h.top());`` ` `        ``h.push(``6``);``        ``h.push(``4``);``        ``h.print_heap();``        ``System.out.println(h.size());`` ` `        ``h.pop();``        ``h.print_heap();``        ``System.out.println(h.size());``    ``}``}`` ` `// This code is contributed by lokeshmvs21.`

C#

 `// C# code for the above approach`` ` `using` `System;`` ` `class` `Heap {``    ``private` `int``[] heap = ``new` `int``[100];``    ``private` `int` `heapsize = -1;`` ` `    ``// Heapify up function``    ``private` `void` `Heapifyup()``    ``{``        ``int` `i = heapsize;``        ``while` `(i >= 0) {``            ``if` `(heap[i] <= heap[(i - 1) / 2]) {``                ``break``;``            ``}``            ``else` `{``                ``int` `temp = heap[i];``                ``heap[i] = heap[(i - 1) / 2];``                ``heap[(i - 1) / 2] = temp;``            ``}``            ``i = (i - 1) / 2;``        ``}``    ``}`` ` `    ``// Heapify down function``    ``private` `void` `Heapifydown()``    ``{``        ``int` `i = 0;``        ``while` `(i != heapsize) {``            ``if` `(heap[i] >= Math.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);``                ``int` `temp = heap[i];``                ``heap[i] = heap[k];``                ``heap[k] = temp;``                ``i = k;``            ``}``        ``}``    ``}`` ` `    ``// Push function to insert a value into the heap``    ``public` `void` `push(``int` `val)``    ``{``        ``heapsize++;``        ``heap[heapsize] = val;``        ``Heapifyup();``    ``}`` ` `    ``// Pop function to remove the root element from the heap``    ``public` `void` `pop()``    ``{``        ``if` `(heapsize < 0) {``            ``Console.WriteLine(``"Heap Underflow"``);``            ``return``;``        ``}``        ``heap[0] = heap[heapsize];``        ``heapsize--;``        ``if` `(heapsize > 0) {``            ``Heapifydown();``        ``}``    ``}`` ` `    ``// Print_heap function to print the elements in the heap``    ``public` `void` `print_heap()``    ``{``        ``for` `(``int` `i = 0; i <= heapsize; i++) {``            ``Console.Write(heap[i] + ``" "``);``        ``}``        ``Console.WriteLine();``    ``}`` ` `    ``// Size function to return the size of the heap``    ``public` `int` `size() { ``return` `heapsize + 1; }`` ` `    ``// Top function to return the root element of the heap``    ``public` `int` `top()``    ``{``        ``if` `(heapsize < 0) {``            ``return` `-1;``        ``}``        ``return` `heap[0];``    ``}``}`` ` `class` `GFG {`` ` `    ``// Driver code``    ``static` `void` `Main(``string``[] args)``    ``{``        ``Heap h = ``new` `Heap();``        ``Console.WriteLine(h.top());``        ``Console.WriteLine(h.size());``        ``h.print_heap();`` ` `        ``h.pop();``        ``h.push(5);``        ``h.push(7);``        ``Console.WriteLine(h.top());`` ` `        ``h.push(6);``        ``h.push(4);``        ``h.print_heap();``        ``Console.WriteLine(h.size());`` ` `        ``h.pop();``        ``h.print_heap();``        ``Console.WriteLine(h.size());``    ``}``}`` ` `// This code is contributed by phasing17.`

Javascript

 `// javascript code implementation `` ` `const N = 100;`` ` `// Heap Structure..``class Heap {``     ` `    ``constructor(){``        ``this``.heap = ``new` `Array(N).fill(0);``        ``this``.heapsize = -1;``    ``}`` ` `     ` `    ``Heapifyup()``    ``{``        ``let i = ``this``.heapsize;``        ``let j;``        ``while` `(i >= 0) {``            ``let x = Math.floor((i == 0) ? 0:(i-1)/2);``            ``if` `(``this``.heap[i] <= ``this``.heap[x]) {``                ``break``;``            ``}``            ``else` `{``                 ` `                ``// swapping heap[i], heap[j]``                ``let temp = ``this``.heap[i];``                ``this``.heap[i] = ``this``.heap[x];``                ``this``.heap[(i == 0)? 0:(i-1)/2] = temp;``            ``}``            ``i = Math.floor(i == 0 ? 0: (i-1)/2);``        ``}``    ``}``     ` `    ``Heapifydown()``    ``{``        ``let i = 0;``        ``while` `(i != ``this``.heapsize) {`` ` `            ``if` `(``this``.heap[i] >= Math.max(``this``.heap[2 * i + 1], ``this``.heap[2 * i + 2])) {``                ``break``;``            ``}``            ``else` `{``                ``let k = (``this``.heap[2 * i + 1] >= ``this``.heap[2 * i + 2]) ? 2 * i + 1 : 2 * i + 2;``                 ` `                ``// swapping heap[i] and heap[k]``                ``let temp = ``this``.heap[i];``                ``this``.heap[i] = ``this``.heap[k];``                ``this``.heap[k] = temp;``                ``i = k;``            ``}``        ``}``    ``}`` ` `    ``push(val)``    ``{``        ``this``.heapsize = ``this``.heapsize + 1;``        ``this``.heap[``this``.heapsize] = val;``        ``this``.Heapifyup();``    ``}``     ` `    ``pop()``    ``{``        ``if` `(``this``.heapsize < 0) {``            ``console.log(``"Heap Underflow"``);``            ``return``;``        ``}``        ``this``.heap[0] = ``this``.heap[``this``.heapsize];``        ``this``.heapsize = ``this``.heapsize - 1;``        ``if` `(``this``.heapsize > 0) {``            ``this``.Heapifydown();``            ``// heapify top down``        ``}``    ``}``     ` `    ``print_heap()``    ``{``        ``for` `(let i = 0; i <= ``this``.heapsize; i++) {``            ``process.stdout.write(``this``.heap[i] + ``" "``);``        ``}``        ``console.log()``    ``}``     ` `    ``size(){``        ``return` `this``.heapsize + 1; ``    ``}``    ``top()``    ``{``        ``// console.log(this.heap);``        ``if` `(``this``.heapsize < 0) {``            ``return` `-1;``        ``}``        ``return` `this``.heap[0];``    ``}``};`` ` `// Driver code`` ` `let h = ``new` `Heap();``console.log(h.top());``console.log(h.size());``h.print_heap();`` ` `h.pop();``h.push(5);``h.push(7);``console.log(h.top());`` ` `h.push(6);``h.push(4);``h.print_heap();``console.log(h.size());`` ` `h.pop();``h.print_heap();``console.log(h.size());`` ` `// The code is contributed by Nidhi goel.`

Output

```-1
0

Heap Underflow
7
7 5 6 4
4
6 5 4
3```

Below is the implementation of the Min-Heap Data Structure

C++

 `#include ``using` `namespace` `std;``#define N 100``// Heap Structure..``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]``                ``<= min(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();``        ``// heapify bottom up``    ``}``    ``void` `pop()``    ``{``        ``if` `(heapsize < 0) {``            ``cout << ``"Heap Underflow \n"``;``            ``return``;``        ``}``        ``heap[0] = heap[heapsize];``        ``heapsize--;``        ``if` `(heapsize > 0) {``            ``Heapifydown();``            ``// heapify top down``        ``}``    ``}``    ``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;``}`

Output

```-1
0

Heap Underflow
5
4 5 6 7
4
5 7 6
3```

The Heap:

The Heap” refers to the dynamic memory as an alternative to the local stack memory. Local memory is quite automatic. Local variables are allocated automatically when a function is called, and they are deallocated automatically when the function exits. Heap memory is different in every way.

1. It allows us to access variables globally.
2.  Does not have a specific limit on memory size.
3. Variables can be resized in any instance.
4. Memory allocated by the heap is not contiguous rather is allocated in any random order.

1. Heap space is not used as efficiently. Memory can become fragmented as blocks of memory are first allocated and then freed.
2. Slower execution compared to stack
3. Allocation is manually done by the programmers so explicit de-allocation is needed.

Below is the implementation of using Heap Memory:

C++

 `#include ``using` `namespace` `std;`` ` `int` `main()``{``    ``int``* arr = ``new` `int``[5]; ``// initializing array using heap memory`` ` `    ``// arr= {0, 1, 2, 3, 4}``    ``for` `(``int` `i = 0; i < 5; i++) {``        ``arr[i] = i;``    ``}``    ``cout << *arr << endl; ``// pointer always points to first element of an array  the first element`` ` `    ``cout << *(arr + 1) << endl;`` ` `    ``return` `0;``}`

Java

 `import` `java.util.Arrays;`` ` `public` `class` `Main {``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int``[] arr = ``new` `int``[``5``]; ``// initializing array using stack memory`` ` `        ``// arr = {0, 1, 2, 3, 4}``        ``for` `(``int` `i = ``0``; i < ``5``; i++) {``            ``arr[i] = i;``        ``}``        ``System.out.println(arr[``0``]); ``// the first element of the array`` ` `        ``System.out.println(arr[``1``]);``    ``}``}`

Output

```0
1```

Time Complexity: O(1)
Auxiliary Space: O(1)

Related Articles:

My Personal Notes arrow_drop_up