import static org.junit.Assert. import java.util.ArrayList import org.junit.Befo
ID: 3742520 • Letter: I
Question
import static org.junit.Assert. import java.util.ArrayList import org.junit.Before: import org junit.Testi public class MaxHeapTest private MaxHeap heap: eBefore public void setUp) throws Exception heap new MaxHeap (10) heap.insert (new Student("Susan", 60, 3.5)) heap.insert (new Student("Ben 70. 3.4)) heap.insert (new Student( "Reed, 120, 4.0)) heap.insert (new student "Johnny",50, 1.2) Test public void test assertEquals (4.0, heap.extractMax().gpa000001) assertEquals (3.5, heap.extractMax().gpa), .000001)Explanation / Answer
Please find the code below.
CODE
===================
public void insert(Student elt) {
students.add(student);
int current = students.size();
while(students.get(current) > students.get(parent(current))) {
swap(current, parent(current));
current = parent(current);
}
}
public void changeKey(Student s, double newGPA) {
int indexOfStudent = students.indexOf(s);
if(indexOfStudent != -1) {
s.setGPA(newGPA);
students.set(indexOfStudent, s);
}
}
Test methods
====================
@Test
public void testIfInsertionHappenedCorrectly() {
assertEquals(4, heap.size(), 0.000001);
// insert a new student with max GPA
heap.insert(new Student("Joe", 120, 4.5));
// now check if the extract Max return Student Joe
Student s = heap.extractMax();
assertEquals(5, heap.size(), 0.000001);
assertEquals(4.5, s.getGPA, 0.000001);
}
@Test
public void testIfChangeKeyWorksCorrectly() {
Student s = new Student("Joe", 120, 4.5);
// insert a student with max GPA
heap.insert(s);
//now change key
heap.change(s, 2.5);
// check that extract Max returns different student now
Student max = heap.extractMax();
assertEquals(4, max.getGPA(), 0.000001);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.