Question
I need some help in my code. This is an in-place heap-tree and I got some problem with finish the methods. I hope you could
I need some help in my code.
This is an in-place heap-tree and I got some problem with finish the methods.
I hope you could help me to finish it or just write a new one.
The program includes insert() and remove()
Please try to insert(5, A), insert(4, B), insert(7, F), insert(1, D), remove(Min) and show the result by screenshot.
public class HeapTree {
private int[] data;
private int heapSize;
public BinaryMinHeap(int size) {
data = new int[size];
heapSize = 0;
}
public int getMinimum() {
if (isEmpty())
throw new HeapException("Heap is empty");
else
return data[0];
}
public boolean isEmpty() {
return (heapSize == 0);
}
private int getLeftChildIndex(int nodeIndex) {
return 2 * nodeIndex + 1;
}
private int getRightChildIndex(int nodeIndex) {
return 2 * nodeIndex + 2;
}
private int getParentIndex(int nodeIndex) {
return (nodeIndex - 1) / 2;
}
public class HeapException extends RuntimeException {
public HeapException(String message) {
super(message);
}
public void removeMin() {
if (isEmpty())
throw new HeapException("Heap is empty");
else {
data[0] = data[heapSize - 1];
heapSize--;
if (heapSize > 0)
siftDown(0);
}
}
public void insert(int value) {
if (heapSize == data.length)
throw new HeapException("Heap's underlying storage is overflow");
else {
heapSize++;
data[heapSize - 1] = value;
siftUp(heapSize - 1);
}
}
private void siftDown(int nodeIndex) {
int leftChildIndex, rightChildIndex, minIndex, tmp;
leftChildIndex = getLeftChildIndex(nodeIndex);
rightChildIndex = getRightChildIndex(nodeIndex);
if (rightChildIndex >= heapSize) {
if (leftChildIndex >= heapSize)
return;
else
minIndex = leftChildIndex;
} else {
if (data[leftChildIndex] <= data[rightChildIndex])
minIndex = leftChildIndex;
else
minIndex = rightChildIndex;
}
if (data[nodeIndex] > data[minIndex]) {
tmp = data[minIndex];
data[minIndex] = data[nodeIndex];
data[nodeIndex] = tmp;
siftDown(minIndex);
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started