SlideShare une entreprise Scribd logo
1  sur  4
public class HeapPriorityQueue <K extends Comparable, V> implements PriorityQueue <K, V>
{
private Entry [] storage; //The Heap itself in array form
private int tail; //Index of last element in the heap
public HeapPriorityQueue() {this(100);}
public HeapPriorityQueue( int size ) {
storage = new Entry [ size ];
tail = -1;}
public int size() {return tail + 1;}
public Entry <K, V>insert( K key, V value) throws IllegalArgumentException {
if( tail == storage.length - 1 )
throw new IllegalArgumentException ( "Heap Overflow" );
Entry <K, V> e = new Entry <> ( key, value );
storage [ ++tail ] = e;
e.setIndex(tail);
upHeap ( tail );
return e;
public Entry <K, V> min() {
if( isEmpty() )
return null;
return storage [ 0 ];
}
public Entry <K, V> removeMin() {
if( isEmpty() )
return null;
Entry <K, V> ret = storage [ 0 ];
if( tail == 0 ) {
tail = -1;
storage [ 0 ] = null;
return ret;
}
private void upHeap( int location ) {
if( location == 0 ) return;
int parent = parent ( location );
if( storage [ parent ].key.compareTo ( storage [ location ].key ) > 0 ) {
swap ( location, parent );
upHeap ( parent );
}
}
private void downHeap( int location ) {
int left = (location * 2) + 1;
int right = (location * 2) + 2;
//Both children null or out of bound
if( left > tail ) return;
//left in right out;
if( left == tail ) {
if( storage [ location ].key.compareTo ( storage [ left ].key ) > 0 )
swap ( location, left );
return;
}
int toSwap = (storage [ left ].key.compareTo ( storage [ right ].key ) < 0) ?
left : right;
if( storage [ location ].key.compareTo ( storage [ toSwap ].key ) > 0 ) {
swap ( location, toSwap );
downHeap ( toSwap );
}
}
private int parent( int location ) {
return (location - 1) / 2;
}
private void swap( int location1, int location2 ) {
Entry <K, V> temp = storage [ location1 ];
storage [ location1 ] = storage [ location2 ];
storage [ location2 ] = temp;
storage[location1].index= location1;
storage[location2].index= location2;
}
public void print() {
for (Entry<K,V> e : storage)
System.out.println ( "(" + e.key.toString() + "," + e.value.toString() + ":" + e.index + "), " );
}
}
public class HeapPriorityQueueTest {
static String alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static void main( String [] args ) {
Random rng = new Random(12345); // do not change the seed
// A min-heap
HeapPriorityQueue <Integer, Character> pq = new HeapPriorityQueue <> ( 500 );
// Insert elements in heap
for( int i = 0; i < 100; i++ ) {
Entry <Integer, Character> e= pq.insert ( rng.nextInt ( 10000 ), alpha.charAt ( rng.nextInt ( 52 )
));
}
System.out.println();System.out.println();
// removeMin
for( int i = 0; i < 8; i++ ) {
Entry <Integer, Character> e = pq.removeMin();
System.out.print ( "(" + e.key.toString() + "," + e.value.toString() + ":" + e.index + "), " );
}
System.out.println();System.out.println();
// removeMax
/*
for( int i = 0; i < 8; i++ ) {
Entry <Integer, Character> e = pq.removeMax();
System.out.print ( "(" + e.key.toString() + "," + e.value.toString() + ":" + e.index + "), " );
}
*/
System.out.println();System.out.println();
// removeMin
for( int i = 0; i < 8; i++ ) {
Entry <Integer, Character> e = pq.removeMin();
System.out.print ( "(" + e.key.toString() + "," + e.value.toString() + ":" + e.index + "), " );
}
System.out.println();System.out.println();
// removeMax
/*
for( int i = 0; i < 8; i++ ) {
Entry <Integer, Character> e = pq.removeMax();
System.out.print ( "(" + e.key.toString() + "," + e.value.toString() + ":" + e.index + "), " );
}
*/
}
}
The objective of this programming assignment is to implement a double-ended priority queue;
this is a priority queue for which you can obtain both the max and the min element. This double-
ended queue will be implemented using two heaps: a min-heap and a max-heap. Half of the
elements are stored in one of the heaps and the other half is stored in the second heap. Each
element a of the min-heap is associated with one element of the max-heap b with a < b . If the
total number of elements is odd, then the extra element is contained in a 1-element buffer. The
min element removal Removing the min element is done as follows: 1. Check the element at the
root of the min-heap, if this one is greater than the element in the buffer (if any) then simply
return the element in the buffer 2. Else you remove and return the element at the root of the min-
heap. The associated element in the max-heap must now be re-processed. a. If the buffer is
empty, then remove the element to be re-processed from the maxheap and insert it in the buffer
b. If the buffer is not empty, then the element to be re-processed and the element in the buffer
must now form a new pair. c. If the element in the buffer is smaller than the element to be re-
processed, then you simply have to insert the element in the buffer into the min-heap. d. If the
element in the buffer is greater than the element to be re-processed, then i . these two elements
must exchange their values ii. the max-heap must be modified in order to re-establish the heap
condition. iii. the element in the buffer must be inserted in the min-heap. The max element
removal Removing the max element is done by following the same procedure as for the removal
of the min element as explained above, except that it now operates from the max-heap.
Instructions: To build your solution, start from the code provided that implements a regular min-
heap. The index attribute in the Entry class provides the current position of the element in the
array. The associate attribute is currently not used. There is also a test main function in the
HeapPriorityQueueTest class. Do not modify this class but you will uncomment the section that
calls the removeMax method that you have to implement. You must follow the algorithm
described above. For step 2 of the removal step, you will have to design an algorithm that allows
to re-establish the heap condition when a node at any position is mispositioned. Note that you
can assume that there will not be 2 keys with the same value in the two heaps.

Contenu connexe

Similaire à public class HeapPriorityQueue -K extends Comparable- V- implements Pr (1).docx

Writing native bindings to node.js in C++
Writing native bindings to node.js in C++Writing native bindings to node.js in C++
Writing native bindings to node.js in C++nsm.nikhil
 
Please review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdfPlease review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdffathimafancyjeweller
 
package algs13;import stdlib.;import java.util.Iterator;im.docx
package algs13;import  stdlib.;import java.util.Iterator;im.docxpackage algs13;import  stdlib.;import java.util.Iterator;im.docx
package algs13;import stdlib.;import java.util.Iterator;im.docxgerardkortney
 
OBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .pptOBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .pptSaadAsim11
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguageSamir Chekkal
 
Is java8 a true functional programming language
Is java8 a true functional programming languageIs java8 a true functional programming language
Is java8 a true functional programming languageSQLI
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfravikapoorindia
 
AnswerNote Driver class is not given to test the DoubleArraySeq..pdf
AnswerNote Driver class is not given to test the DoubleArraySeq..pdfAnswerNote Driver class is not given to test the DoubleArraySeq..pdf
AnswerNote Driver class is not given to test the DoubleArraySeq..pdfnipuns1983
 
USING JAVAThere are at least two types of nearly sorted array.pdf
USING JAVAThere are at least two types of nearly sorted array.pdfUSING JAVAThere are at least two types of nearly sorted array.pdf
USING JAVAThere are at least two types of nearly sorted array.pdflohithkart
 
Write a method replaceKey in the BinaryHeap class with the following .docx
 Write a method replaceKey in the BinaryHeap class with the following .docx Write a method replaceKey in the BinaryHeap class with the following .docx
Write a method replaceKey in the BinaryHeap class with the following .docxajoy21
 
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxNew folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxcurwenmichaela
 
PriorityQueue.cs Jim Mischel using System; using Sy.pdf
 PriorityQueue.cs   Jim Mischel using System; using Sy.pdf PriorityQueue.cs   Jim Mischel using System; using Sy.pdf
PriorityQueue.cs Jim Mischel using System; using Sy.pdfrajat630669
 
Describe a data structure that supports both removeMin() and rem.pdf
Describe a data structure that supports both removeMin() and rem.pdfDescribe a data structure that supports both removeMin() and rem.pdf
Describe a data structure that supports both removeMin() and rem.pdfarihantstoneart
 
Create a Dynamic Array container with this user interface Ge.pdf
Create a Dynamic Array container with this user interface  Ge.pdfCreate a Dynamic Array container with this user interface  Ge.pdf
Create a Dynamic Array container with this user interface Ge.pdfsktambifortune
 

Similaire à public class HeapPriorityQueue -K extends Comparable- V- implements Pr (1).docx (20)

LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++Writing native bindings to node.js in C++
Writing native bindings to node.js in C++
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Please review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdfPlease review my code (java)Someone helped me with it but i cannot.pdf
Please review my code (java)Someone helped me with it but i cannot.pdf
 
Heaps
HeapsHeaps
Heaps
 
package algs13;import stdlib.;import java.util.Iterator;im.docx
package algs13;import  stdlib.;import java.util.Iterator;im.docxpackage algs13;import  stdlib.;import java.util.Iterator;im.docx
package algs13;import stdlib.;import java.util.Iterator;im.docx
 
OBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .pptOBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .ppt
 
Lec2
Lec2Lec2
Lec2
 
Is java8a truefunctionallanguage
Is java8a truefunctionallanguageIs java8a truefunctionallanguage
Is java8a truefunctionallanguage
 
Is java8 a true functional programming language
Is java8 a true functional programming languageIs java8 a true functional programming language
Is java8 a true functional programming language
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdf
 
AnswerNote Driver class is not given to test the DoubleArraySeq..pdf
AnswerNote Driver class is not given to test the DoubleArraySeq..pdfAnswerNote Driver class is not given to test the DoubleArraySeq..pdf
AnswerNote Driver class is not given to test the DoubleArraySeq..pdf
 
USING JAVAThere are at least two types of nearly sorted array.pdf
USING JAVAThere are at least two types of nearly sorted array.pdfUSING JAVAThere are at least two types of nearly sorted array.pdf
USING JAVAThere are at least two types of nearly sorted array.pdf
 
Lab 1
Lab 1Lab 1
Lab 1
 
stack presentation
stack presentationstack presentation
stack presentation
 
Write a method replaceKey in the BinaryHeap class with the following .docx
 Write a method replaceKey in the BinaryHeap class with the following .docx Write a method replaceKey in the BinaryHeap class with the following .docx
Write a method replaceKey in the BinaryHeap class with the following .docx
 
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxNew folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
 
PriorityQueue.cs Jim Mischel using System; using Sy.pdf
 PriorityQueue.cs   Jim Mischel using System; using Sy.pdf PriorityQueue.cs   Jim Mischel using System; using Sy.pdf
PriorityQueue.cs Jim Mischel using System; using Sy.pdf
 
Describe a data structure that supports both removeMin() and rem.pdf
Describe a data structure that supports both removeMin() and rem.pdfDescribe a data structure that supports both removeMin() and rem.pdf
Describe a data structure that supports both removeMin() and rem.pdf
 
Create a Dynamic Array container with this user interface Ge.pdf
Create a Dynamic Array container with this user interface  Ge.pdfCreate a Dynamic Array container with this user interface  Ge.pdf
Create a Dynamic Array container with this user interface Ge.pdf
 

Plus de EdwardEkRChapmann

Q-5 Peyon Recaves 10-000 as a Gift FRem Huver her Mothen and She waxts.docx
Q-5 Peyon Recaves 10-000 as a Gift FRem Huver her Mothen and She waxts.docxQ-5 Peyon Recaves 10-000 as a Gift FRem Huver her Mothen and She waxts.docx
Q-5 Peyon Recaves 10-000 as a Gift FRem Huver her Mothen and She waxts.docxEdwardEkRChapmann
 
Q- No-01 Kedzie Kord Company reported market price of its share as $50.docx
Q- No-01 Kedzie Kord Company reported market price of its share as $50.docxQ- No-01 Kedzie Kord Company reported market price of its share as $50.docx
Q- No-01 Kedzie Kord Company reported market price of its share as $50.docxEdwardEkRChapmann
 
Q- (i1) Quinn Age is invests 20-000 in a Sey fund Contract and makes A.docx
Q- (i1) Quinn Age is invests 20-000 in a Sey fund Contract and makes A.docxQ- (i1) Quinn Age is invests 20-000 in a Sey fund Contract and makes A.docx
Q- (i1) Quinn Age is invests 20-000 in a Sey fund Contract and makes A.docxEdwardEkRChapmann
 
Q!-(18) Edmond an ins agent meebs lelly who wants to purchese a whele.docx
Q!-(18) Edmond an ins agent meebs lelly who wants to purchese a whele.docxQ!-(18) Edmond an ins agent meebs lelly who wants to purchese a whele.docx
Q!-(18) Edmond an ins agent meebs lelly who wants to purchese a whele.docxEdwardEkRChapmann
 
Python Key Value Store Design Properly implement an application with a.docx
Python Key Value Store Design Properly implement an application with a.docxPython Key Value Store Design Properly implement an application with a.docx
Python Key Value Store Design Properly implement an application with a.docxEdwardEkRChapmann
 
Puestion 6 if itolmiti 3) Trie aj falun Question 7(4 soints) 11- mupat.docx
Puestion 6 if itolmiti 3) Trie aj falun Question 7(4 soints) 11- mupat.docxPuestion 6 if itolmiti 3) Trie aj falun Question 7(4 soints) 11- mupat.docx
Puestion 6 if itolmiti 3) Trie aj falun Question 7(4 soints) 11- mupat.docxEdwardEkRChapmann
 
public class ExampleCode2 { public static void countDown1(int num) {.docx
public class ExampleCode2 {   public static void countDown1(int num) {.docxpublic class ExampleCode2 {   public static void countDown1(int num) {.docx
public class ExampleCode2 { public static void countDown1(int num) {.docxEdwardEkRChapmann
 
Provide the Total Table Encoded file size for the image pictured that (1).docx
Provide the Total Table Encoded file size for the image pictured that (1).docxProvide the Total Table Encoded file size for the image pictured that (1).docx
Provide the Total Table Encoded file size for the image pictured that (1).docxEdwardEkRChapmann
 
Provide an appropriate response- A university must choose a team of 6.docx
Provide an appropriate response- A university must choose a team of 6.docxProvide an appropriate response- A university must choose a team of 6.docx
Provide an appropriate response- A university must choose a team of 6.docxEdwardEkRChapmann
 
Prove x is even (x+1)2 is odd (hint- use a direct proof).docx
Prove x is even (x+1)2 is odd (hint- use a direct proof).docxProve x is even (x+1)2 is odd (hint- use a direct proof).docx
Prove x is even (x+1)2 is odd (hint- use a direct proof).docxEdwardEkRChapmann
 
Protein utilization by bacteria leads to generation of end products th.docx
Protein utilization by bacteria leads to generation of end products th.docxProtein utilization by bacteria leads to generation of end products th.docx
Protein utilization by bacteria leads to generation of end products th.docxEdwardEkRChapmann
 
Project Scope Statement for the MXE Project Introduction - The purpo.docx
Project Scope Statement for the MXE Project   Introduction - The purpo.docxProject Scope Statement for the MXE Project   Introduction - The purpo.docx
Project Scope Statement for the MXE Project Introduction - The purpo.docxEdwardEkRChapmann
 
Project Closing Document The purpose of this document is to capture.docx
Project Closing Document   The purpose of this document is to capture.docxProject Closing Document   The purpose of this document is to capture.docx
Project Closing Document The purpose of this document is to capture.docxEdwardEkRChapmann
 
Problem II - Control of gastric acidity- 1- What is the trigger to tar.docx
Problem II - Control of gastric acidity- 1- What is the trigger to tar.docxProblem II - Control of gastric acidity- 1- What is the trigger to tar.docx
Problem II - Control of gastric acidity- 1- What is the trigger to tar.docxEdwardEkRChapmann
 
Problem B (5 points)- The health board of a major city wants to know i.docx
Problem B (5 points)- The health board of a major city wants to know i.docxProblem B (5 points)- The health board of a major city wants to know i.docx
Problem B (5 points)- The health board of a major city wants to know i.docxEdwardEkRChapmann
 
Problem B part a Suppose A-B are events with indicators IA-IB- What va.docx
Problem B part a Suppose A-B are events with indicators IA-IB- What va.docxProblem B part a Suppose A-B are events with indicators IA-IB- What va.docx
Problem B part a Suppose A-B are events with indicators IA-IB- What va.docxEdwardEkRChapmann
 
Problem 8 and 9 Entropy is closely related to something known as Kolmo.docx
Problem 8 and 9 Entropy is closely related to something known as Kolmo.docxProblem 8 and 9 Entropy is closely related to something known as Kolmo.docx
Problem 8 and 9 Entropy is closely related to something known as Kolmo.docxEdwardEkRChapmann
 
Problem 4-45 (LO- 4) Nell and Kirby are in the process of negotiating.docx
Problem 4-45 (LO- 4) Nell and Kirby are in the process of negotiating.docxProblem 4-45 (LO- 4) Nell and Kirby are in the process of negotiating.docx
Problem 4-45 (LO- 4) Nell and Kirby are in the process of negotiating.docxEdwardEkRChapmann
 
Problem 3- Reynolds number (Problem 7 of the textbook) (4 points) A sa.docx
Problem 3- Reynolds number (Problem 7 of the textbook) (4 points) A sa.docxProblem 3- Reynolds number (Problem 7 of the textbook) (4 points) A sa.docx
Problem 3- Reynolds number (Problem 7 of the textbook) (4 points) A sa.docxEdwardEkRChapmann
 
Problem 2 (20 points- graded on accuracy) Consider a circle of radius.docx
Problem 2 (20 points- graded on accuracy) Consider a circle of radius.docxProblem 2 (20 points- graded on accuracy) Consider a circle of radius.docx
Problem 2 (20 points- graded on accuracy) Consider a circle of radius.docxEdwardEkRChapmann
 

Plus de EdwardEkRChapmann (20)

Q-5 Peyon Recaves 10-000 as a Gift FRem Huver her Mothen and She waxts.docx
Q-5 Peyon Recaves 10-000 as a Gift FRem Huver her Mothen and She waxts.docxQ-5 Peyon Recaves 10-000 as a Gift FRem Huver her Mothen and She waxts.docx
Q-5 Peyon Recaves 10-000 as a Gift FRem Huver her Mothen and She waxts.docx
 
Q- No-01 Kedzie Kord Company reported market price of its share as $50.docx
Q- No-01 Kedzie Kord Company reported market price of its share as $50.docxQ- No-01 Kedzie Kord Company reported market price of its share as $50.docx
Q- No-01 Kedzie Kord Company reported market price of its share as $50.docx
 
Q- (i1) Quinn Age is invests 20-000 in a Sey fund Contract and makes A.docx
Q- (i1) Quinn Age is invests 20-000 in a Sey fund Contract and makes A.docxQ- (i1) Quinn Age is invests 20-000 in a Sey fund Contract and makes A.docx
Q- (i1) Quinn Age is invests 20-000 in a Sey fund Contract and makes A.docx
 
Q!-(18) Edmond an ins agent meebs lelly who wants to purchese a whele.docx
Q!-(18) Edmond an ins agent meebs lelly who wants to purchese a whele.docxQ!-(18) Edmond an ins agent meebs lelly who wants to purchese a whele.docx
Q!-(18) Edmond an ins agent meebs lelly who wants to purchese a whele.docx
 
Python Key Value Store Design Properly implement an application with a.docx
Python Key Value Store Design Properly implement an application with a.docxPython Key Value Store Design Properly implement an application with a.docx
Python Key Value Store Design Properly implement an application with a.docx
 
Puestion 6 if itolmiti 3) Trie aj falun Question 7(4 soints) 11- mupat.docx
Puestion 6 if itolmiti 3) Trie aj falun Question 7(4 soints) 11- mupat.docxPuestion 6 if itolmiti 3) Trie aj falun Question 7(4 soints) 11- mupat.docx
Puestion 6 if itolmiti 3) Trie aj falun Question 7(4 soints) 11- mupat.docx
 
public class ExampleCode2 { public static void countDown1(int num) {.docx
public class ExampleCode2 {   public static void countDown1(int num) {.docxpublic class ExampleCode2 {   public static void countDown1(int num) {.docx
public class ExampleCode2 { public static void countDown1(int num) {.docx
 
Provide the Total Table Encoded file size for the image pictured that (1).docx
Provide the Total Table Encoded file size for the image pictured that (1).docxProvide the Total Table Encoded file size for the image pictured that (1).docx
Provide the Total Table Encoded file size for the image pictured that (1).docx
 
Provide an appropriate response- A university must choose a team of 6.docx
Provide an appropriate response- A university must choose a team of 6.docxProvide an appropriate response- A university must choose a team of 6.docx
Provide an appropriate response- A university must choose a team of 6.docx
 
Prove x is even (x+1)2 is odd (hint- use a direct proof).docx
Prove x is even (x+1)2 is odd (hint- use a direct proof).docxProve x is even (x+1)2 is odd (hint- use a direct proof).docx
Prove x is even (x+1)2 is odd (hint- use a direct proof).docx
 
Protein utilization by bacteria leads to generation of end products th.docx
Protein utilization by bacteria leads to generation of end products th.docxProtein utilization by bacteria leads to generation of end products th.docx
Protein utilization by bacteria leads to generation of end products th.docx
 
Project Scope Statement for the MXE Project Introduction - The purpo.docx
Project Scope Statement for the MXE Project   Introduction - The purpo.docxProject Scope Statement for the MXE Project   Introduction - The purpo.docx
Project Scope Statement for the MXE Project Introduction - The purpo.docx
 
Project Closing Document The purpose of this document is to capture.docx
Project Closing Document   The purpose of this document is to capture.docxProject Closing Document   The purpose of this document is to capture.docx
Project Closing Document The purpose of this document is to capture.docx
 
Problem II - Control of gastric acidity- 1- What is the trigger to tar.docx
Problem II - Control of gastric acidity- 1- What is the trigger to tar.docxProblem II - Control of gastric acidity- 1- What is the trigger to tar.docx
Problem II - Control of gastric acidity- 1- What is the trigger to tar.docx
 
Problem B (5 points)- The health board of a major city wants to know i.docx
Problem B (5 points)- The health board of a major city wants to know i.docxProblem B (5 points)- The health board of a major city wants to know i.docx
Problem B (5 points)- The health board of a major city wants to know i.docx
 
Problem B part a Suppose A-B are events with indicators IA-IB- What va.docx
Problem B part a Suppose A-B are events with indicators IA-IB- What va.docxProblem B part a Suppose A-B are events with indicators IA-IB- What va.docx
Problem B part a Suppose A-B are events with indicators IA-IB- What va.docx
 
Problem 8 and 9 Entropy is closely related to something known as Kolmo.docx
Problem 8 and 9 Entropy is closely related to something known as Kolmo.docxProblem 8 and 9 Entropy is closely related to something known as Kolmo.docx
Problem 8 and 9 Entropy is closely related to something known as Kolmo.docx
 
Problem 4-45 (LO- 4) Nell and Kirby are in the process of negotiating.docx
Problem 4-45 (LO- 4) Nell and Kirby are in the process of negotiating.docxProblem 4-45 (LO- 4) Nell and Kirby are in the process of negotiating.docx
Problem 4-45 (LO- 4) Nell and Kirby are in the process of negotiating.docx
 
Problem 3- Reynolds number (Problem 7 of the textbook) (4 points) A sa.docx
Problem 3- Reynolds number (Problem 7 of the textbook) (4 points) A sa.docxProblem 3- Reynolds number (Problem 7 of the textbook) (4 points) A sa.docx
Problem 3- Reynolds number (Problem 7 of the textbook) (4 points) A sa.docx
 
Problem 2 (20 points- graded on accuracy) Consider a circle of radius.docx
Problem 2 (20 points- graded on accuracy) Consider a circle of radius.docxProblem 2 (20 points- graded on accuracy) Consider a circle of radius.docx
Problem 2 (20 points- graded on accuracy) Consider a circle of radius.docx
 

Dernier

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxNikitaBankoti2
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesShubhangi Sonawane
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
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
 
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
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 

Dernier (20)

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
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
 
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 ...
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 

public class HeapPriorityQueue -K extends Comparable- V- implements Pr (1).docx

  • 1. public class HeapPriorityQueue <K extends Comparable, V> implements PriorityQueue <K, V> { private Entry [] storage; //The Heap itself in array form private int tail; //Index of last element in the heap public HeapPriorityQueue() {this(100);} public HeapPriorityQueue( int size ) { storage = new Entry [ size ]; tail = -1;} public int size() {return tail + 1;} public Entry <K, V>insert( K key, V value) throws IllegalArgumentException { if( tail == storage.length - 1 ) throw new IllegalArgumentException ( "Heap Overflow" ); Entry <K, V> e = new Entry <> ( key, value ); storage [ ++tail ] = e; e.setIndex(tail); upHeap ( tail ); return e; public Entry <K, V> min() { if( isEmpty() ) return null; return storage [ 0 ]; } public Entry <K, V> removeMin() { if( isEmpty() ) return null; Entry <K, V> ret = storage [ 0 ]; if( tail == 0 ) { tail = -1; storage [ 0 ] = null; return ret; } private void upHeap( int location ) { if( location == 0 ) return; int parent = parent ( location ); if( storage [ parent ].key.compareTo ( storage [ location ].key ) > 0 ) { swap ( location, parent ); upHeap ( parent ); } } private void downHeap( int location ) {
  • 2. int left = (location * 2) + 1; int right = (location * 2) + 2; //Both children null or out of bound if( left > tail ) return; //left in right out; if( left == tail ) { if( storage [ location ].key.compareTo ( storage [ left ].key ) > 0 ) swap ( location, left ); return; } int toSwap = (storage [ left ].key.compareTo ( storage [ right ].key ) < 0) ? left : right; if( storage [ location ].key.compareTo ( storage [ toSwap ].key ) > 0 ) { swap ( location, toSwap ); downHeap ( toSwap ); } } private int parent( int location ) { return (location - 1) / 2; } private void swap( int location1, int location2 ) { Entry <K, V> temp = storage [ location1 ]; storage [ location1 ] = storage [ location2 ]; storage [ location2 ] = temp; storage[location1].index= location1; storage[location2].index= location2; } public void print() { for (Entry<K,V> e : storage) System.out.println ( "(" + e.key.toString() + "," + e.value.toString() + ":" + e.index + "), " ); } } public class HeapPriorityQueueTest { static String alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static void main( String [] args ) { Random rng = new Random(12345); // do not change the seed
  • 3. // A min-heap HeapPriorityQueue <Integer, Character> pq = new HeapPriorityQueue <> ( 500 ); // Insert elements in heap for( int i = 0; i < 100; i++ ) { Entry <Integer, Character> e= pq.insert ( rng.nextInt ( 10000 ), alpha.charAt ( rng.nextInt ( 52 ) )); } System.out.println();System.out.println(); // removeMin for( int i = 0; i < 8; i++ ) { Entry <Integer, Character> e = pq.removeMin(); System.out.print ( "(" + e.key.toString() + "," + e.value.toString() + ":" + e.index + "), " ); } System.out.println();System.out.println(); // removeMax /* for( int i = 0; i < 8; i++ ) { Entry <Integer, Character> e = pq.removeMax(); System.out.print ( "(" + e.key.toString() + "," + e.value.toString() + ":" + e.index + "), " ); } */ System.out.println();System.out.println(); // removeMin for( int i = 0; i < 8; i++ ) { Entry <Integer, Character> e = pq.removeMin(); System.out.print ( "(" + e.key.toString() + "," + e.value.toString() + ":" + e.index + "), " ); } System.out.println();System.out.println(); // removeMax /* for( int i = 0; i < 8; i++ ) { Entry <Integer, Character> e = pq.removeMax(); System.out.print ( "(" + e.key.toString() + "," + e.value.toString() + ":" + e.index + "), " ); } */ } }
  • 4. The objective of this programming assignment is to implement a double-ended priority queue; this is a priority queue for which you can obtain both the max and the min element. This double- ended queue will be implemented using two heaps: a min-heap and a max-heap. Half of the elements are stored in one of the heaps and the other half is stored in the second heap. Each element a of the min-heap is associated with one element of the max-heap b with a < b . If the total number of elements is odd, then the extra element is contained in a 1-element buffer. The min element removal Removing the min element is done as follows: 1. Check the element at the root of the min-heap, if this one is greater than the element in the buffer (if any) then simply return the element in the buffer 2. Else you remove and return the element at the root of the min- heap. The associated element in the max-heap must now be re-processed. a. If the buffer is empty, then remove the element to be re-processed from the maxheap and insert it in the buffer b. If the buffer is not empty, then the element to be re-processed and the element in the buffer must now form a new pair. c. If the element in the buffer is smaller than the element to be re- processed, then you simply have to insert the element in the buffer into the min-heap. d. If the element in the buffer is greater than the element to be re-processed, then i . these two elements must exchange their values ii. the max-heap must be modified in order to re-establish the heap condition. iii. the element in the buffer must be inserted in the min-heap. The max element removal Removing the max element is done by following the same procedure as for the removal of the min element as explained above, except that it now operates from the max-heap. Instructions: To build your solution, start from the code provided that implements a regular min- heap. The index attribute in the Entry class provides the current position of the element in the array. The associate attribute is currently not used. There is also a test main function in the HeapPriorityQueueTest class. Do not modify this class but you will uncomment the section that calls the removeMax method that you have to implement. You must follow the algorithm described above. For step 2 of the removal step, you will have to design an algorithm that allows to re-establish the heap condition when a node at any position is mispositioned. Note that you can assume that there will not be 2 keys with the same value in the two heaps.