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 <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;
}
|
Java
import java.io.*;
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();
}
void pop()
{
if (heapsize < 0) {
System.out.println("Heap Underflow ");
return;
}
heap[0] = heap[heapsize];
heapsize--;
if (heapsize > 0) {
Heapifydown();
}
}
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());
}
}
|
Python3
N = 100
class Heap:
def __init__(self):
self.heap = [0] * N
self.heapsize = -1
def Heapifyup(self):
i = self.heapsize
while i >= 0:
x = (i - 1) // 2 if i != 0 else 0
if self.heap[i] <= self.heap[x]:
break
else:
temp = self.heap[i]
self.heap[i] = self.heap[x]
self.heap[x] = temp
i = (i - 1) // 2
def Heapifydown(self):
i = 0
while i != self.heapsize:
k = 2 * i + 1 if self.heap[2 * i + 1] >= self.heap[2 * i + 2] else 2 * i + 2
if self.heap[i] >= self.heap[k]:
break
else:
temp = self.heap[i]
self.heap[i] = self.heap[k]
self.heap[k] = temp
i = k
def push(self, val):
self.heapsize += 1
self.heap[self.heapsize] = val
self.Heapifyup()
def pop(self):
if self.heapsize < 0:
print("Heap Underflow")
return
self.heap[0] = self.heap[self.heapsize]
self.heapsize -= 1
if self.heapsize > 0:
self.Heapifydown()
def print_heap(self):
for i in range(self.heapsize + 1):
print(self.heap[i], end=" ")
print()
def size(self):
return self.heapsize + 1
def top(self):
if self.heapsize < 0:
return -1
return self.heap[0]
h = Heap()
print(h.top())
print(h.size())
h.print_heap()
h.pop()
h.push(5)
h.push(7)
print(h.top())
h.push(6)
h.push(4)
h.print_heap()
print(h.size())
h.pop()
h.print_heap()
print(h.size())
|
C#
using System;
class Heap {
private int[] heap = new int[100];
private int heapsize = -1;
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;
}
}
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;
}
}
}
public void push(int val)
{
heapsize++;
heap[heapsize] = val;
Heapifyup();
}
public void pop()
{
if (heapsize < 0) {
Console.WriteLine("Heap Underflow");
return;
}
heap[0] = heap[heapsize];
heapsize--;
if (heapsize > 0) {
Heapifydown();
}
}
public void print_heap()
{
for (int i = 0; i <= heapsize; i++) {
Console.Write(heap[i] + " ");
}
Console.WriteLine();
}
public int size() { return heapsize + 1; }
public int top()
{
if (heapsize < 0) {
return -1;
}
return heap[0];
}
}
class GFG {
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());
}
}
|
Javascript
const N = 100;
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 {
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;
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();
}
}
print_heap()
{
for (let i = 0; i <= this.heapsize; i++) {
process.stdout.write(this.heap[i] + " ");
}
console.log()
}
size(){
return this.heapsize + 1;
}
top()
{
if (this.heapsize < 0) {
return -1;
}
return this.heap[0];
}
};
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());
|
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 <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]
<= 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();
}
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;
}
|
Python3
import heapq
class Heap:
def __init__(self):
self.heap = []
def push(self, val):
heapq.heappush(self.heap, val)
def pop(self):
if not self.heap:
print("Heap Underflow")
return
heapq.heappop(self.heap)
def print_heap(self):
print(self.heap)
def size(self):
return len(self.heap)
def top(self):
if not self.heap:
return -1
return self.heap[0]
if __name__ == '__main__':
h = Heap()
print(h.top())
print(h.size())
h.print_heap()
h.pop()
h.push(5)
h.push(7)
print(h.top())
h.push(6)
h.push(4)
h.print_heap()
print(h.size())
h.pop()
h.print_heap()
print(h.size())
|
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.
Advantages of Using Heap Memory:
- It allows us to access variables globally.
- Does not have a specific limit on memory size.
- Variables can be resized in any instance.
- Memory allocated by the heap is not contiguous rather is allocated in any random order.
Disadvantages of Using Heap Memory:
- Heap space is not used as efficiently. Memory can become fragmented as blocks of memory are first allocated and then freed.
- Slower execution compared to stack
- Allocation is manually done by the programmers so explicit de-allocation is needed.
Below is the implementation of using Heap Memory:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int* arr = new int[5];
for (int i = 0; i < 5; i++) {
arr[i] = i;
}
cout << *arr << endl;
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];
for (int i = 0; i < 5; i++) {
arr[i] = i;
}
System.out.println(arr[0]);
System.out.println(arr[1]);
}
}
|
C#
using System;
public class MainClass {
public static void Main(string[] args)
{
int[] arr = new int[5];
for (int i = 0; i < 5; i++) {
arr[i] = i;
}
Console.WriteLine(arr[0]);
Console.WriteLine(arr[1]);
}
}
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Related Articles:
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
19 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...