0% found this document useful (0 votes)
44 views4 pages

Heap Data Structure Program:: Max Heap Refer Notes For The Theory This Is An Example of Heapify

This document provides code examples for implementing a max heap data structure using an ArrayList in Java. It includes methods for heapifying a node in the heap, inserting a new number into the heap, and deleting a node from the heap while maintaining the heap property.

Uploaded by

Taufik Pirjade
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views4 pages

Heap Data Structure Program:: Max Heap Refer Notes For The Theory This Is An Example of Heapify

This document provides code examples for implementing a max heap data structure using an ArrayList in Java. It includes methods for heapifying a node in the heap, inserting a new number into the heap, and deleting a node from the heap while maintaining the heap property.

Uploaded by

Taufik Pirjade
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Heap Data Structure Program:

Max Heap

Refer Notes for the theory

This is an example of Heapify :

void heapify(ArrayList<Integer> hT, int i) {


int size = hT.size();
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < size && hT.get(l) > hT.get(largest))
largest = l;
if (r < size && hT.get(r) > hT.get(largest))
largest = r;

if (largest != i) {
int temp = hT.get(largest);
hT.set(largest, hT.get(i));
hT.set(i, temp);

heapify(hT, largest);
}
}

void insert(ArrayList<Integer> hT, int newNum) {


int size = hT.size();
if (size == 0) {
hT.add(newNum);
} else {
hT.add(newNum);
for (int i = size / 2 - 1; i >= 0; i--) {
heapify(hT, i);
}
}
}

void deleteNode(ArrayList<Integer> hT, int num)


{
int size = hT.size();
int i;
for (i = 0; i < size; i++)
{
if (num == hT.get(i))
break;
}

int temp = hT.get(i);


hT.set(i, hT.get(size-1));
hT.set(size-1, temp);

hT.remove(size-1);
for (int j = size / 2 - 1; j >= 0; j--)
{
heapify(hT, j);
}
}

You might also like