Question: I got some problem in the code. Hope you can help me to finish the code. It is a heap tree in java. Do not

I got some problem in the code. Hope you can help me to finish the code.

It is a heap tree in java.

Do not just copy and past a new code

public class MinHeap

{

private int[] Heap;

private int size;

private int maxsize;

private static final int FRONT = 1;

public MinHeap(int maxsize)

{

this.maxsize = maxsize;

this.size = 0;

Heap = new int[this.maxsize + 1];

Heap[0] = Integer.MIN_VALUE;

}

private int parent(int pos)

{

return pos / 2;

}

private int leftChild(int pos)

{

return (2 * pos);

}

private int rightChild(int pos)

{

return (2 * pos) + 1;

}

private boolean isLeaf(int pos)

{

if (pos >= (size / 2) && pos <= size)

{

return true;

}

return false;

}

private void swap(int fpos, int spos)

{

int tmp;

tmp = Heap[fpos];

Heap[fpos] = Heap[spos];

Heap[spos] = tmp;

}

private void minHeapify(int pos)

{

if (!isLeaf(pos))

{

if ( Heap[pos] > Heap[leftChild(pos)] || Heap[pos] > Heap[rightChild(pos)])

{

if (Heap[leftChild(pos)] < Heap[rightChild(pos)])

{

swap(pos, leftChild(pos));

minHeapify(leftChild(pos));

}else

{

swap(pos, rightChild(pos));

minHeapify(rightChild(pos));

}

}

}

}

public void insert(int element)

{

Heap[++size] = element;

int current = size;

while (Heap[current] < Heap[parent(current)])

{

swap(current,parent(current));

current = parent(current);

}

}

public void print()

{

for (int i = 1; i <= size; i++ )

{

System.out.print(Heap[i]);

System.out.print(" ");

}

}

public void minHeap()

{

for (int pos = (size / 2); pos >= 1 ; pos--)

{

minHeapify(pos);

}

}

public int remove()

{

int popped = Heap[FRONT];

Heap[FRONT] = Heap[size--];

minHeapify(FRONT);

return popped;

}

public static void main(String...arg)

{

System.out.println("The Min Heap is ");

MinHeap minHeap = new MinHeap(15);

minHeap.insert(5,k);

minHeap.insert(3,j);

minHeap.insert(17,a);

minHeap.insert(10,b);

minHeap.insert(84,q);

minHeap.insert(19,w);

minHeap.insert(6,e);

minHeap.insert(22,n);

minHeap.insert(9,c);

minHeap.print();

System.out.println();

minHeap.remove();

minHeap.print();

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!