leturn pårentIndex; // Problem Heap 4 20 points // Write a method that adds an i
ID: 3739534 • Letter: L
Question
leturn pårentIndex; // Problem Heap 4 20 points // Write a method that adds an item to the heap. // To add an item to the heap, add it to the first empty spot in the arrayList // Then while the item is smaller than it's parent, swap it with it's parent Remember, there are no gaps between items in the array // // You will need to use compareTo You do not need to worry about resizing the heap, since the ArrayList does that for you public void add (E item) t size++i // use this main to test public static void main (String[l args) fExplanation / Answer
MaxHeap.java
public class MaxHeap {
public int[] myHeap = new int[20];
public int begin = 0;
public int current = 0;
public int getParent(int index){
return (index - 1)/2;
}
public int getLeftChild(int index){
return 2*index+1;
}
public int getRighChild(int index){
return 2*index+2;
}
public void insert(int data) {
myHeap[current] = data;
int i = current;
int tmp;
int parent;
while(i > 0){
parent = getParent(i);
System.out.println(" I value"+i+" parent"+parent+" data"+data);
if(myHeap[parent] < myHeap[i]){
tmp = myHeap[parent];
myHeap[parent] = myHeap[i];
myHeap[i] = tmp;
} else{
break;
}
i = parent;
}
current++;
}
}
TestFile
public class MaxHeapTest {
public void main(String [] args) {
MaxHeap myHeap = new MaxHeap();
myHeap.insert(40);
myHeap.insert(20);
myHeap.insert(10);
myHeap.insert(25);
myHeap.insert(30);
myHeap.insert(100);
for(int i = 0; i < myHeap.current;i++){
System.out.println(" "+myHeap.myHeap[i]);
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.