SlideShare a Scribd company logo
Listings for BinaryHeap.java and BinaryHeapTest.java are shown in the menu at left
Everything in the BinaryHeap class has been written except the add and remove methods, which
you must write:
First, implement add, then run the test class and observe the testAdd results
Next, implement remove, then run the test class and observe the testRemove results
testAdd and testRemove should both run without errors
Note:
A comp object implementing the Comparator interface is passed to the binary heap's
constructor. You will need to use the comp object's compare method when making comparisons
in the add and remove operations.
The parent, leftChild, and rightChild methods in BinaryHeapTest are for testing purposes only,
and should not be used to implement add and remove
Solution
BinaryHeapTest.java
import java.util.Comparator;
import org.junit.Test;
import static org.junit.Assert.*;
public class BinaryHeapTest {
/**
* A binary heap of Integer objects
*/
private BinaryHeap bh;
/**
* Some Integer nodes for testing
*/
private Integer n1, n2, n3, n4, n5, n6, n7, n8, n9, n10;
/**
* An object for comparing Integer nodes
*/
private Comparator comp;
public BinaryHeapTest() {
comp = new Comparator() {
public int compare(Integer t, Integer t1) {
return t.compareTo(t1);
}
};
bh = new BinaryHeap(10, comp);
n1 = new Integer(1);
n2 = new Integer(2);
n3 = new Integer(3);
n4 = new Integer(4);
n5 = new Integer(5);
n6 = new Integer(6);
n7 = new Integer(7);
n8 = new Integer(8);
n9 = new Integer(9);
n10 = new Integer(10);
}
@Test
public void testAdd() {
buildHeap();
assertTrue(leftChild(n1) == n2);
assertTrue(rightChild(n1) == n5);
assertTrue(leftChild(n2) == n4);
assertTrue(rightChild(n2) == n3);
assertTrue(leftChild(n5) == n9);
assertTrue(rightChild(n5) == n6);
assertTrue(leftChild(n4) == n10);
assertTrue(rightChild(n4) == n7);
assertTrue(leftChild(n3) == n8);
assertTrue(rightChild(n3) == null);
assertTrue(leftChild(n9) == null);
assertTrue(rightChild(n9) == null);
assertTrue(leftChild(n6) == null);
assertTrue(rightChild(n6) == null);
assertTrue(parent(n10) == n4);
assertTrue(parent(n7) == n4);
assertTrue(parent(n8) == n3);
assertTrue(parent(n4) == n2);
assertTrue(parent(n3) == n2);
assertTrue(parent(n9) == n5);
assertTrue(parent(n6) == n5);
assertTrue(parent(n2) == n1);
assertTrue(parent(n5) == n1);
assertTrue(parent(n1) == null);
}
/**
* An auxiliary method that builds a heap that should look like:
*
* 1
* / 
* 2 5
* /  / 
* 4 3 9 6
* /  /
* 10 7 8
*/
private void buildHeap() {
bh.clear();
assertTrue(bh.isEmpty());
bh.add(n10);
bh.add(n9);
bh.add(n8);
bh.add(n7);
bh.add(n6);
bh.add(n5);
bh.add(n4);
bh.add(n3);
bh.add(n2);
bh.add(n1);
assertTrue(bh.size() == 10);
}
@Test
public void testRemove() {
buildHeap();
assertTrue(bh.remove() == n1);
assertTrue(bh.remove() == n2);
assertTrue(bh.remove() == n3);
assertTrue(bh.remove() == n4);
assertTrue(bh.remove() == n5);
assertTrue(bh.remove() == n6);
assertTrue(bh.remove() == n7);
assertTrue(bh.remove() == n8);
assertTrue(bh.remove() == n9);
assertTrue(bh.remove() == n10);
assertTrue(bh.isEmpty());
}
private Object leftChild(Object element) {
int index = bh.indexOf(element) * 2;
if (outOfRange(index)) {
return null;
} else {
return bh.get(index);
}
}
private Object rightChild(Object element) {
int index = bh.indexOf(element) * 2 + 1;
if (outOfRange(index)) {
return null;
} else {
return bh.get(index);
}
}
private Object parent(Object element) {
int index = bh.indexOf(element) / 2;
if (outOfRange(index)) {
return null;
} else {
return bh.get(index);
}
}
private boolean outOfRange(int index) {
return index < 1 || index > bh.size();
}
}
BinaryHeap.java
import java.util.ArrayList;
import java.util.Comparator;
public class BinaryHeap extends ArrayList {
/**
* Creates an empty binary heap with a given capacity and comparator.
* @param capacity The initial size of the underlying ArrayList object.
* @param comp A comparator object for comparing keys of binary heap elements.
*/
public BinaryHeap(int capacity, Comparator comp) {
super(capacity+1);
init();
this.comp = comp;
}
/**
* Initializes the underlying ArrayList object for use as a binary heap.
* A null object is added to location 0, which is not used by the heap.
*/
private void init() {
add(0, null);
}
/**
* Clears this binary heap by clearing and initializing the underlying
* ArrayList object.
*/
public void clear() {
super.clear();
init();
}
public int size() {
return super.size()-1;
}
/**
* Returns true if this binary heap is empty, that is, its size is zero.
* @return Whether this binary heap is empty.
*/
public boolean isEmpty() {
return size() == 0;
}
public boolean add(E element) {
//System.out.println(size());
// You must provide
add(size()+1,element);
bubbleUp();
return true;
}
public E remove() {
E returned = get(1);
System.out.println("root: " + returned.toString());
// You must provide
System.out.println("size: "+ size());
set(1,get(size()));
// set(size(),null);
this.remove(size());
bubbleDown();
return returned;
}
private void bubbleDown() {
int index = 1;
// bubble down
while (hasLeftChild(index)) {
// which of my children is smaller?
int smallerChild = leftIndex(index);
if (hasRightChild(index)
&&(comp.compare(get(leftIndex(index)),get(rightIndex(index)))>0)){ //
array[leftIndex(index)].compareTo(array[rightIndex(index)]) > 0) {
smallerChild = rightIndex(index);
}
if (comp.compare(get(index),get(smallerChild))>0){
//array[index].compareTo(array[smallerChild]) > 0) {
swap(index, smallerChild);
}
else {
break;
}
index = smallerChild;
}
}
private int leftIndex(int i) {
return i * 2;
}
private int rightIndex(int i) {
return i * 2 + 1;
}
private boolean hasLeftChild(int i) {
return leftIndex(i) <= size();
}
private boolean hasRightChild(int i) {
return rightIndex(i) <= size();
}
private void swap(int index1, int index2) {
E tmp = get(index1);
set(index1,get(index2));
set(index2, tmp);
}
private E parent(int i) {
return get(parentIndex(i));
}
private int parentIndex(int i) {
return i / 2;
}
private void bubbleUp() {
int index = size();
// System.out.println("index: " + index);
// System.out.println("bubble up : " +size());
while (hasParent(index)
&& (comp.compare(parent(index),get(index)) >0)) {
// parent/child are out of order; swap them
swap(index, parentIndex(index));
index = parentIndex(index);
}
}
private boolean hasParent(int i) {
return i > 1;
}
/**
* A Comparator object used to compare binary heap elements during its
* add and remove operations.
*/
private Comparator comp;
}

More Related Content

Similar to Listings for BinaryHeap.java and BinaryHeapTest.java are shown in th.pdf

Best Java Problems and Solutions
Best Java Problems and SolutionsBest Java Problems and Solutions
Best Java Problems and Solutions
Java Projects
 
I need help creating a parametized JUnit test case for the following.pdf
I need help creating a parametized JUnit test case for the following.pdfI need help creating a parametized JUnit test case for the following.pdf
I need help creating a parametized JUnit test case for the following.pdf
fonecomp
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdf
akkhan101
 
First C++ code written... I think its quite efficient with all the.pdf
First C++ code written... I think its quite efficient with all the.pdfFirst C++ code written... I think its quite efficient with all the.pdf
First C++ code written... I think its quite efficient with all the.pdf
ankit482504
 
operating system linux,ubuntu,Mac Geometri.pdf
operating system linux,ubuntu,Mac Geometri.pdfoperating system linux,ubuntu,Mac Geometri.pdf
operating system linux,ubuntu,Mac Geometri.pdf
aquadreammail
 
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfImplement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
kostikjaylonshaewe47
 
Given the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdfGiven the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdf
illyasraja7
 
java write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdfjava write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdf
arjuntelecom26
 
Lezione03
Lezione03Lezione03
Lezione03
robynho86
 
Google guava
Google guavaGoogle guava
So I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfSo I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdf
aksahnan
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards
Denis Ristic
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdf
amazing2001
 
Lab 1
Lab 1Lab 1
Need Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdfNeed Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdf
archiesgallery
 
Evolutionary Nursery
Evolutionary NurseryEvolutionary Nursery
Evolutionary Nursery
adil raja
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
Anıl Sözeri
 
all i need is these two filesCreate VectorContainer.hppCreat.docx
all i need is these two filesCreate VectorContainer.hppCreat.docxall i need is these two filesCreate VectorContainer.hppCreat.docx
all i need is these two filesCreate VectorContainer.hppCreat.docx
jack60216
 
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxNew folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
curwenmichaela
 

Similar to Listings for BinaryHeap.java and BinaryHeapTest.java are shown in th.pdf (20)

Best Java Problems and Solutions
Best Java Problems and SolutionsBest Java Problems and Solutions
Best Java Problems and Solutions
 
I need help creating a parametized JUnit test case for the following.pdf
I need help creating a parametized JUnit test case for the following.pdfI need help creating a parametized JUnit test case for the following.pdf
I need help creating a parametized JUnit test case for the following.pdf
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdf
 
First C++ code written... I think its quite efficient with all the.pdf
First C++ code written... I think its quite efficient with all the.pdfFirst C++ code written... I think its quite efficient with all the.pdf
First C++ code written... I think its quite efficient with all the.pdf
 
operating system linux,ubuntu,Mac Geometri.pdf
operating system linux,ubuntu,Mac Geometri.pdfoperating system linux,ubuntu,Mac Geometri.pdf
operating system linux,ubuntu,Mac Geometri.pdf
 
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfImplement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
 
Given the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdfGiven the following codepackage data1;import java.util.;p.pdf
Given the following codepackage data1;import java.util.;p.pdf
 
java write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdfjava write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdf
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lezione03
Lezione03Lezione03
Lezione03
 
Google guava
Google guavaGoogle guava
Google guava
 
So I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfSo I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdf
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdf
 
Lab 1
Lab 1Lab 1
Lab 1
 
Need Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdfNeed Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdf
 
Evolutionary Nursery
Evolutionary NurseryEvolutionary Nursery
Evolutionary Nursery
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 
all i need is these two filesCreate VectorContainer.hppCreat.docx
all i need is these two filesCreate VectorContainer.hppCreat.docxall i need is these two filesCreate VectorContainer.hppCreat.docx
all i need is these two filesCreate VectorContainer.hppCreat.docx
 
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxNew folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
 

More from RAJATCHUGH12

Why is the T7 polymerase gene in E. coli strain BL21(DE3) under the .pdf
Why is the T7 polymerase gene in E. coli strain BL21(DE3) under the .pdfWhy is the T7 polymerase gene in E. coli strain BL21(DE3) under the .pdf
Why is the T7 polymerase gene in E. coli strain BL21(DE3) under the .pdf
RAJATCHUGH12
 
What type of utility program is designed to automatically make dupli.pdf
What type of utility program is designed to automatically make dupli.pdfWhat type of utility program is designed to automatically make dupli.pdf
What type of utility program is designed to automatically make dupli.pdf
RAJATCHUGH12
 
Which of the following is true of xylem conducts water up the plant .pdf
Which of the following is true of xylem conducts water up the plant .pdfWhich of the following is true of xylem conducts water up the plant .pdf
Which of the following is true of xylem conducts water up the plant .pdf
RAJATCHUGH12
 
What are the essential elements to have in BRDR plansWhen is a d.pdf
What are the essential elements to have in BRDR plansWhen is a d.pdfWhat are the essential elements to have in BRDR plansWhen is a d.pdf
What are the essential elements to have in BRDR plansWhen is a d.pdf
RAJATCHUGH12
 
Javaa. The mean of a list of numbers is its arithmetic average. T.pdf
Javaa. The mean of a list of numbers is its arithmetic average. T.pdfJavaa. The mean of a list of numbers is its arithmetic average. T.pdf
Javaa. The mean of a list of numbers is its arithmetic average. T.pdf
RAJATCHUGH12
 
What is the characteristic of the ring of quaternionsSolutionQ.pdf
What is the characteristic of the ring of quaternionsSolutionQ.pdfWhat is the characteristic of the ring of quaternionsSolutionQ.pdf
What is the characteristic of the ring of quaternionsSolutionQ.pdf
RAJATCHUGH12
 
What are the four basic categories of output A. Instructions, pictu.pdf
What are the four basic categories of output  A. Instructions, pictu.pdfWhat are the four basic categories of output  A. Instructions, pictu.pdf
What are the four basic categories of output A. Instructions, pictu.pdf
RAJATCHUGH12
 
vapour pressure equation The Clansius-Clapeyron relation relates the.pdf
vapour pressure equation The Clansius-Clapeyron relation relates the.pdfvapour pressure equation The Clansius-Clapeyron relation relates the.pdf
vapour pressure equation The Clansius-Clapeyron relation relates the.pdf
RAJATCHUGH12
 
What is a test cross and why is it used What technology is essential.pdf
What is a test cross and why is it used What technology is essential.pdfWhat is a test cross and why is it used What technology is essential.pdf
What is a test cross and why is it used What technology is essential.pdf
RAJATCHUGH12
 
What are homologous traits a. Traits that are functional and adapti.pdf
What are homologous traits a. Traits that are functional and adapti.pdfWhat are homologous traits a. Traits that are functional and adapti.pdf
What are homologous traits a. Traits that are functional and adapti.pdf
RAJATCHUGH12
 
The Vietnam War EraDiscuss the range of American responses to the .pdf
The Vietnam War EraDiscuss the range of American responses to the .pdfThe Vietnam War EraDiscuss the range of American responses to the .pdf
The Vietnam War EraDiscuss the range of American responses to the .pdf
RAJATCHUGH12
 
The distance between two successive minimize of a transverse wave.pdf
The distance between two successive minimize of a transverse wave.pdfThe distance between two successive minimize of a transverse wave.pdf
The distance between two successive minimize of a transverse wave.pdf
RAJATCHUGH12
 
t hether each of the following statements are true or false T F Stok.pdf
t hether each of the following statements are true or false T F Stok.pdft hether each of the following statements are true or false T F Stok.pdf
t hether each of the following statements are true or false T F Stok.pdf
RAJATCHUGH12
 
Rewrite the expression as an algebraic expression of x Rewrite the .pdf
Rewrite the expression as an algebraic expression of x Rewrite the .pdfRewrite the expression as an algebraic expression of x Rewrite the .pdf
Rewrite the expression as an algebraic expression of x Rewrite the .pdf
RAJATCHUGH12
 
Need help answering these. Underline the correct answer The fundame.pdf
Need help answering these. Underline the correct answer  The fundame.pdfNeed help answering these. Underline the correct answer  The fundame.pdf
Need help answering these. Underline the correct answer The fundame.pdf
RAJATCHUGH12
 
Origins of psychologyWhen did it begin as a science 1879.pdf
Origins of psychologyWhen did it begin as a science 1879.pdfOrigins of psychologyWhen did it begin as a science 1879.pdf
Origins of psychologyWhen did it begin as a science 1879.pdf
RAJATCHUGH12
 
In hypothesis testing, what is a Type I error Type II errorSol.pdf
In hypothesis testing, what is a Type I error Type II errorSol.pdfIn hypothesis testing, what is a Type I error Type II errorSol.pdf
In hypothesis testing, what is a Type I error Type II errorSol.pdf
RAJATCHUGH12
 
I am stuck on parts E and FExercise 1      NumberListTester.java.pdf
I am stuck on parts E and FExercise 1      NumberListTester.java.pdfI am stuck on parts E and FExercise 1      NumberListTester.java.pdf
I am stuck on parts E and FExercise 1      NumberListTester.java.pdf
RAJATCHUGH12
 
How does differ from evolution systematic Only cladistics traces e.pdf
How does  differ from evolution systematic  Only cladistics traces e.pdfHow does  differ from evolution systematic  Only cladistics traces e.pdf
How does differ from evolution systematic Only cladistics traces e.pdf
RAJATCHUGH12
 
Giving your lawn more nutrients than it can absorb, can cause polluti.pdf
Giving your lawn more nutrients than it can absorb, can cause polluti.pdfGiving your lawn more nutrients than it can absorb, can cause polluti.pdf
Giving your lawn more nutrients than it can absorb, can cause polluti.pdf
RAJATCHUGH12
 

More from RAJATCHUGH12 (20)

Why is the T7 polymerase gene in E. coli strain BL21(DE3) under the .pdf
Why is the T7 polymerase gene in E. coli strain BL21(DE3) under the .pdfWhy is the T7 polymerase gene in E. coli strain BL21(DE3) under the .pdf
Why is the T7 polymerase gene in E. coli strain BL21(DE3) under the .pdf
 
What type of utility program is designed to automatically make dupli.pdf
What type of utility program is designed to automatically make dupli.pdfWhat type of utility program is designed to automatically make dupli.pdf
What type of utility program is designed to automatically make dupli.pdf
 
Which of the following is true of xylem conducts water up the plant .pdf
Which of the following is true of xylem conducts water up the plant .pdfWhich of the following is true of xylem conducts water up the plant .pdf
Which of the following is true of xylem conducts water up the plant .pdf
 
What are the essential elements to have in BRDR plansWhen is a d.pdf
What are the essential elements to have in BRDR plansWhen is a d.pdfWhat are the essential elements to have in BRDR plansWhen is a d.pdf
What are the essential elements to have in BRDR plansWhen is a d.pdf
 
Javaa. The mean of a list of numbers is its arithmetic average. T.pdf
Javaa. The mean of a list of numbers is its arithmetic average. T.pdfJavaa. The mean of a list of numbers is its arithmetic average. T.pdf
Javaa. The mean of a list of numbers is its arithmetic average. T.pdf
 
What is the characteristic of the ring of quaternionsSolutionQ.pdf
What is the characteristic of the ring of quaternionsSolutionQ.pdfWhat is the characteristic of the ring of quaternionsSolutionQ.pdf
What is the characteristic of the ring of quaternionsSolutionQ.pdf
 
What are the four basic categories of output A. Instructions, pictu.pdf
What are the four basic categories of output  A. Instructions, pictu.pdfWhat are the four basic categories of output  A. Instructions, pictu.pdf
What are the four basic categories of output A. Instructions, pictu.pdf
 
vapour pressure equation The Clansius-Clapeyron relation relates the.pdf
vapour pressure equation The Clansius-Clapeyron relation relates the.pdfvapour pressure equation The Clansius-Clapeyron relation relates the.pdf
vapour pressure equation The Clansius-Clapeyron relation relates the.pdf
 
What is a test cross and why is it used What technology is essential.pdf
What is a test cross and why is it used What technology is essential.pdfWhat is a test cross and why is it used What technology is essential.pdf
What is a test cross and why is it used What technology is essential.pdf
 
What are homologous traits a. Traits that are functional and adapti.pdf
What are homologous traits a. Traits that are functional and adapti.pdfWhat are homologous traits a. Traits that are functional and adapti.pdf
What are homologous traits a. Traits that are functional and adapti.pdf
 
The Vietnam War EraDiscuss the range of American responses to the .pdf
The Vietnam War EraDiscuss the range of American responses to the .pdfThe Vietnam War EraDiscuss the range of American responses to the .pdf
The Vietnam War EraDiscuss the range of American responses to the .pdf
 
The distance between two successive minimize of a transverse wave.pdf
The distance between two successive minimize of a transverse wave.pdfThe distance between two successive minimize of a transverse wave.pdf
The distance between two successive minimize of a transverse wave.pdf
 
t hether each of the following statements are true or false T F Stok.pdf
t hether each of the following statements are true or false T F Stok.pdft hether each of the following statements are true or false T F Stok.pdf
t hether each of the following statements are true or false T F Stok.pdf
 
Rewrite the expression as an algebraic expression of x Rewrite the .pdf
Rewrite the expression as an algebraic expression of x Rewrite the .pdfRewrite the expression as an algebraic expression of x Rewrite the .pdf
Rewrite the expression as an algebraic expression of x Rewrite the .pdf
 
Need help answering these. Underline the correct answer The fundame.pdf
Need help answering these. Underline the correct answer  The fundame.pdfNeed help answering these. Underline the correct answer  The fundame.pdf
Need help answering these. Underline the correct answer The fundame.pdf
 
Origins of psychologyWhen did it begin as a science 1879.pdf
Origins of psychologyWhen did it begin as a science 1879.pdfOrigins of psychologyWhen did it begin as a science 1879.pdf
Origins of psychologyWhen did it begin as a science 1879.pdf
 
In hypothesis testing, what is a Type I error Type II errorSol.pdf
In hypothesis testing, what is a Type I error Type II errorSol.pdfIn hypothesis testing, what is a Type I error Type II errorSol.pdf
In hypothesis testing, what is a Type I error Type II errorSol.pdf
 
I am stuck on parts E and FExercise 1      NumberListTester.java.pdf
I am stuck on parts E and FExercise 1      NumberListTester.java.pdfI am stuck on parts E and FExercise 1      NumberListTester.java.pdf
I am stuck on parts E and FExercise 1      NumberListTester.java.pdf
 
How does differ from evolution systematic Only cladistics traces e.pdf
How does  differ from evolution systematic  Only cladistics traces e.pdfHow does  differ from evolution systematic  Only cladistics traces e.pdf
How does differ from evolution systematic Only cladistics traces e.pdf
 
Giving your lawn more nutrients than it can absorb, can cause polluti.pdf
Giving your lawn more nutrients than it can absorb, can cause polluti.pdfGiving your lawn more nutrients than it can absorb, can cause polluti.pdf
Giving your lawn more nutrients than it can absorb, can cause polluti.pdf
 

Recently uploaded

CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
Col Mukteshwar Prasad
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 

Recently uploaded (20)

CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 

Listings for BinaryHeap.java and BinaryHeapTest.java are shown in th.pdf

  • 1. Listings for BinaryHeap.java and BinaryHeapTest.java are shown in the menu at left Everything in the BinaryHeap class has been written except the add and remove methods, which you must write: First, implement add, then run the test class and observe the testAdd results Next, implement remove, then run the test class and observe the testRemove results testAdd and testRemove should both run without errors Note: A comp object implementing the Comparator interface is passed to the binary heap's constructor. You will need to use the comp object's compare method when making comparisons in the add and remove operations. The parent, leftChild, and rightChild methods in BinaryHeapTest are for testing purposes only, and should not be used to implement add and remove Solution BinaryHeapTest.java import java.util.Comparator; import org.junit.Test; import static org.junit.Assert.*; public class BinaryHeapTest { /** * A binary heap of Integer objects */ private BinaryHeap bh; /** * Some Integer nodes for testing */ private Integer n1, n2, n3, n4, n5, n6, n7, n8, n9, n10; /** * An object for comparing Integer nodes */ private Comparator comp; public BinaryHeapTest() { comp = new Comparator() {
  • 2. public int compare(Integer t, Integer t1) { return t.compareTo(t1); } }; bh = new BinaryHeap(10, comp); n1 = new Integer(1); n2 = new Integer(2); n3 = new Integer(3); n4 = new Integer(4); n5 = new Integer(5); n6 = new Integer(6); n7 = new Integer(7); n8 = new Integer(8); n9 = new Integer(9); n10 = new Integer(10); } @Test public void testAdd() { buildHeap(); assertTrue(leftChild(n1) == n2); assertTrue(rightChild(n1) == n5); assertTrue(leftChild(n2) == n4); assertTrue(rightChild(n2) == n3); assertTrue(leftChild(n5) == n9); assertTrue(rightChild(n5) == n6); assertTrue(leftChild(n4) == n10); assertTrue(rightChild(n4) == n7); assertTrue(leftChild(n3) == n8); assertTrue(rightChild(n3) == null); assertTrue(leftChild(n9) == null); assertTrue(rightChild(n9) == null); assertTrue(leftChild(n6) == null); assertTrue(rightChild(n6) == null); assertTrue(parent(n10) == n4); assertTrue(parent(n7) == n4); assertTrue(parent(n8) == n3);
  • 3. assertTrue(parent(n4) == n2); assertTrue(parent(n3) == n2); assertTrue(parent(n9) == n5); assertTrue(parent(n6) == n5); assertTrue(parent(n2) == n1); assertTrue(parent(n5) == n1); assertTrue(parent(n1) == null); } /** * An auxiliary method that builds a heap that should look like: * * 1 * / * 2 5 * / / * 4 3 9 6 * / / * 10 7 8 */ private void buildHeap() { bh.clear(); assertTrue(bh.isEmpty()); bh.add(n10); bh.add(n9); bh.add(n8); bh.add(n7); bh.add(n6); bh.add(n5); bh.add(n4); bh.add(n3); bh.add(n2); bh.add(n1); assertTrue(bh.size() == 10); } @Test public void testRemove() {
  • 4. buildHeap(); assertTrue(bh.remove() == n1); assertTrue(bh.remove() == n2); assertTrue(bh.remove() == n3); assertTrue(bh.remove() == n4); assertTrue(bh.remove() == n5); assertTrue(bh.remove() == n6); assertTrue(bh.remove() == n7); assertTrue(bh.remove() == n8); assertTrue(bh.remove() == n9); assertTrue(bh.remove() == n10); assertTrue(bh.isEmpty()); } private Object leftChild(Object element) { int index = bh.indexOf(element) * 2; if (outOfRange(index)) { return null; } else { return bh.get(index); } } private Object rightChild(Object element) { int index = bh.indexOf(element) * 2 + 1; if (outOfRange(index)) { return null; } else { return bh.get(index); } } private Object parent(Object element) { int index = bh.indexOf(element) / 2; if (outOfRange(index)) { return null; } else { return bh.get(index); }
  • 5. } private boolean outOfRange(int index) { return index < 1 || index > bh.size(); } } BinaryHeap.java import java.util.ArrayList; import java.util.Comparator; public class BinaryHeap extends ArrayList { /** * Creates an empty binary heap with a given capacity and comparator. * @param capacity The initial size of the underlying ArrayList object. * @param comp A comparator object for comparing keys of binary heap elements. */ public BinaryHeap(int capacity, Comparator comp) { super(capacity+1); init(); this.comp = comp; } /** * Initializes the underlying ArrayList object for use as a binary heap. * A null object is added to location 0, which is not used by the heap. */ private void init() { add(0, null); } /** * Clears this binary heap by clearing and initializing the underlying * ArrayList object. */ public void clear() { super.clear(); init(); }
  • 6. public int size() { return super.size()-1; } /** * Returns true if this binary heap is empty, that is, its size is zero. * @return Whether this binary heap is empty. */ public boolean isEmpty() { return size() == 0; } public boolean add(E element) { //System.out.println(size()); // You must provide add(size()+1,element); bubbleUp(); return true; } public E remove() { E returned = get(1); System.out.println("root: " + returned.toString()); // You must provide System.out.println("size: "+ size()); set(1,get(size())); // set(size(),null); this.remove(size()); bubbleDown(); return returned; } private void bubbleDown() { int index = 1; // bubble down while (hasLeftChild(index)) { // which of my children is smaller?
  • 7. int smallerChild = leftIndex(index); if (hasRightChild(index) &&(comp.compare(get(leftIndex(index)),get(rightIndex(index)))>0)){ // array[leftIndex(index)].compareTo(array[rightIndex(index)]) > 0) { smallerChild = rightIndex(index); } if (comp.compare(get(index),get(smallerChild))>0){ //array[index].compareTo(array[smallerChild]) > 0) { swap(index, smallerChild); } else { break; } index = smallerChild; } } private int leftIndex(int i) { return i * 2; } private int rightIndex(int i) { return i * 2 + 1; } private boolean hasLeftChild(int i) { return leftIndex(i) <= size(); } private boolean hasRightChild(int i) {
  • 8. return rightIndex(i) <= size(); } private void swap(int index1, int index2) { E tmp = get(index1); set(index1,get(index2)); set(index2, tmp); } private E parent(int i) { return get(parentIndex(i)); } private int parentIndex(int i) { return i / 2; } private void bubbleUp() { int index = size(); // System.out.println("index: " + index); // System.out.println("bubble up : " +size()); while (hasParent(index) && (comp.compare(parent(index),get(index)) >0)) { // parent/child are out of order; swap them swap(index, parentIndex(index)); index = parentIndex(index); } } private boolean hasParent(int i) { return i > 1; } /** * A Comparator object used to compare binary heap elements during its
  • 9. * add and remove operations. */ private Comparator comp; }