Java Question Show the contents of an initially empty priority queue after each
ID: 3690723 • Letter: J
Question
Java Question
Show the contents of an initially empty priority queue after each of the following statements execute.
Assume that the first character of the object (the number) specifies its priority. For example, object 1a has priority 1 and object 2b has priority 2.
Lower numbers have higher priorities. So 2b has a higher priority than 3d; 2b has the same priority as 2e.
Put the front of the priority queue on the left and the back on the right.
pq1.add(1d)
pq1.add(2e)
pq1.add(1a)
pq1.add(2a)
pq1.add(1c)
pq1.add(1e);
pq1.remove()
pq1.add(pq1.remove())
pq1.add(pq1.getFront())
pq1.remove()
pq1.remove()
pq1.remove();
pq1.remove();
Explanation / Answer
hey heres the code:
class PriorityQueue
{
int[] heap;
char [] l;
private int heapSize,capacity;
/** Constructor **/
public PriorityQueue(int capacity)
{
this.capacity=capacity;
heap = new int[this.capacity];
l = new char[this.capacity];
heapSize = -1;
}
/** function to clear **/
public void clear()
{
heap = new int[capacity];
l = new char[capacity];
heapSize = -1;
}
/** function to check if empty **/
public boolean isEmpty()
{
return heapSize == -1;
}
/** function to check if full **/
public boolean isFull()
{
return heapSize == capacity;
}
/** function to get Size **/
public int size()
{
return heapSize;
}
/** function to insert task **/
public void add(String priority)
{
if(heapSize==-1)
{
heapSize++;
heap[heapSize]=(int)priority.charAt(0)-48;
l[heapSize]=priority.charAt(1);
}
else
{
heapSize++;
int n=heapSize;
heap[heapSize]=(int)priority.charAt(0)-48;
l[heapSize]=priority.charAt(1);
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(heap[i]<heap[j])
{
int temp=heap[i];
char t=l[i];
heap[i]=heap[j];
l[i]=l[j];
heap[j]=temp;
l[j]=t;
}
}
}
}
}
/** function to remove task **/
public String remove()
{
return Integer.toString(heap[heapSize])+l[heapSize--];
}
public String getFront()
{
return Integer.toString(heap[heapSize])+l[heapSize];
}
}
/** Class PriorityQueueTest **/
public class PriorityQueueTest
{
public static void main(String[] args)
{
System.out.println("Priority Queue Test ");
PriorityQueue pq1 = new PriorityQueue(10 );
pq1.add("1d");
pq1.add("2e");
pq1.add("1a");
pq1.add("2a");
pq1.add("1c");
pq1.add("1e");
System.out.println(pq1.remove());
pq1.add(pq1.remove());
System.out.println(pq1.getFront());
pq1.add(pq1.getFront());
pq1.remove();
pq1.remove();
pq1.remove();
pq1.remove();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.