Question: With the given pseudocode below, how do I translate them into Java and implement them in the following class Heap.java ? 2.1 Inserting into a
With the given pseudocode below, how do I translate them into Java and implement them in the following class Heap.java?
2.1 Inserting into a Heap
Algorithm: maxHeapInsert(heap,heapSize, newItem)
{ heap - an array, heapSize - the number of items
in the heap, newItem - the item to be inserted.}
heap[heapSize] <- newitem place <- heapsize parent <- (place -1)/2
while parent >= 0 and heap[place] > heap[parent]
swap(heap,place,parent) place <- parent parent <- (place - 1)/2
heapSize <- heapSize + 1
________________________________________________
2.2 Deleting from a Heap
Algorithm: maxHeapReheapify(heap,root,heapSize) if root is not a leaf
child <- 2 * root + 1 if root has a right child
if heap[child + 1] > Heap[child])
child <- child + 1
if Heap[root] < Heap[child]
swap(heap,root,child)
MaxHeapReheapify(heap,child,heapSize)
Algorithm: maxHeapDelete(heap) root <- heap[0] heap[0] <- heap[heapSize-1]
heapSize <- heapSize - 1
maxHeapReheapify(heap,0,heapSize)
return root
_________________________________________
Heap.java
import java.util.*;
public class Heap> implements HeapAPI { /** * A complete tree stored in an array list representing this * binary heap */ private ArrayList tree; /** * Constructs an empty heap */ public Heap() { }
public boolean isEmpty() { if (tree.size() == 0) { return true; } return false; }
//Still needs work! public void insert(E obj) { tree.isEmpty; if (tree.isEmpty) { tree.add(obj); } else { tree.add(obj); int place = tree.size(); int parent = (place -1)/2; while(parent >= 0 && (tree.get(place) > (tree.get(parent)) { swap(tree, place, parent) } } place.add(); insert(); }
public E remove() throws HeapException { E root = tree.get(0); tree.set(0 , tree.get(tree.size()-1)); reheapify(0); return root; }
public E peek() throws HeapException { //implement this method }
public int size() { //implement this method } /** * Swaps a parent and child elements of this heap at the specified indices * @param place an index of the child element on this heap * @param parent an index of the parent element on this heap */ private void swap(int place, int parent) { //implement this method }
/** * Rebuilds the heap to ensure that the heap property of the tree is preserved. * @param root the root index of the subtree to be rebuilt */ private void reheapify(int root) { if(root =! ){ } } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
