SlideShare a Scribd company logo
1 of 9
Download to read offline
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 SolutionsJava 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.pdffonecomp
 
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.pdfakkhan101
 
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.pdfankit482504
 
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.pdfaquadreammail
 
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.pdfkostikjaylonshaewe47
 
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.pdfillyasraja7
 
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.pdfarjuntelecom26
 
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.pdfaksahnan
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboardsDenis 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.pdfamazing2001
 
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 .pdfarchiesgallery
 
Evolutionary Nursery
Evolutionary NurseryEvolutionary Nursery
Evolutionary Nurseryadil raja
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming LanguageAnı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.docxjack60216
 
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxNew folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxcurwenmichaela
 

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 .pdfRAJATCHUGH12
 
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.pdfRAJATCHUGH12
 
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 .pdfRAJATCHUGH12
 
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.pdfRAJATCHUGH12
 
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.pdfRAJATCHUGH12
 
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.pdfRAJATCHUGH12
 
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.pdfRAJATCHUGH12
 
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.pdfRAJATCHUGH12
 
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.pdfRAJATCHUGH12
 
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.pdfRAJATCHUGH12
 
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 .pdfRAJATCHUGH12
 
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.pdfRAJATCHUGH12
 
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.pdfRAJATCHUGH12
 
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 .pdfRAJATCHUGH12
 
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.pdfRAJATCHUGH12
 
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.pdfRAJATCHUGH12
 
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.pdfRAJATCHUGH12
 
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.pdfRAJATCHUGH12
 
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.pdfRAJATCHUGH12
 
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.pdfRAJATCHUGH12
 

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

18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 

Recently uploaded (20)

18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 

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; }