Question

In: Computer Science

Given the following program with fill in the blanks, implement the PQ class which is priority...

Given the following program with fill in the blanks, implement the PQ class which is priority Queue MAX heap; the higher the number, the higher the prority of that number. None of the public methods has been implemented. You will need to write other methods to help implement some of the methods. For example you will need to implement bubbleUp to help with the insert method.

Methods to implement:

insert -> insert one element into the PQ and maintain heap shape/ order

remove-> remove the highest priority and maintain heap shape/order

poll -> gets the highest priority without removing

heapify -> build a priority queue from a given list of numbers

toSortedList-> removes all elements from the PQ into a list such that is is sorted from highest to lowest priority.

_________________________________________________________________________________________________________

public class PQimplement {

public static void main(String args[]){

List list = randomList(20);

System.out.println("Unsorted Input List: " + list.toString());

PQ priorityQueue = new PQ(list);

List sortedList = priorityQueue.toSortedList();

System.out.println("Sorted List Descending order: " + list.toString());

}

private static List randomList(int size){

final Random rng = new Random();

List list = new ArrayList<>(size);

for(int i = 0; i< size; i++){

list.add(rng.nextInt()%10);

}

return list;

}

}

public class PQ {
int data[];
int size;
int capacity;
PQ(int capacity){
this.capacity = capacity;
size = 0;
data = new int[capacity];
}
PQ(){
capacity = 1000;
size = 0;
data = new int[capacity];
}
PQ(List data){
capacity = data.size() > 1000 ? data.size() : 1000;
size = data.size();
heapify(data);
}
public void insert(int data){
//Insert the new data into the PQ, ensure the heap maintains heap order/shape
//fill in
}
public void remove(){
//Removes the root or the node with the highest priority
//fill in
}
public int poll(){
//Returns the node with the highest priority. This method should NOT remove that node
//fill in
return -1;
}
private void heapify(List data){
//implement the heapify method that will build a PQ given a list of data
}
public List toSortedList(){
//this method will return a list of all the integers in the priority queue in sorted order (Max Heap)
//this method will remove all the data from the pq
}
}

Solutions

Expert Solution

// PQ.java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class PQ {
  
   int data[];
   int size;
   int capacity;
  
   PQ(int capacity){
       this.capacity = capacity;
       size = 0;
       data = new int[capacity];
   }
  
   PQ(){
       capacity = 1000;
       size = 0;
       data = new int[capacity];
   }
  
   PQ(List<Integer> data){
       capacity = data.size() > 1000 ? data.size() : 1000;
       size = data.size();
       heapify(data);
   }
  
   public void insert(int data){
       //Insert the new data into the PQ, ensure the heap maintains heap order/shape
       if(size == capacity) // array is full
       {
           // expand the array by twice its capacity
           this.data = Arrays.copyOf(this.data, capacity*2);
           capacity = 2*capacity;
       }
      
       // insert the data at the end of the array
       this.data[size] = data;
       bubbleUp(size); // move up the data at the correct position
       size++; // increment the size
      
   }
  
   // private helper method to move the element up to occupy its correct position
   private void bubbleUp(int index)
   {
       int item = data[index]; // get the item at index
       int parent = (index-1)/2; // get the index of its parent
      
       // loop to move the element up so that it occupies its correct position to maintain a MaxHeap
       while(index > 0 && data[parent] < item)
       {
           // set data at index to data at parent
           data[index] = data[parent];
           index = parent; // make index as parent index
           parent = (index-1)/2; // get the index of parent
       }
      
       data[index] = item; // set item at index
   }
  
   // method to remove the maximum priority element
   public void remove(){
       if(size > 0) // array is not empty
       {
           // replace the data at 0 with the last element
           data[0] = data[--size];
           bubbleDown(0); // method to move the element down to its correct position
       }
   }
  
   // helper method to restore the MaxHeap
   private void bubbleDown(int index)
   {
       int left = 2*index+1; // get the index of left child
       int right = 2*index+2; // get the index of right child
      
       int max = index;
      
       // get the index of element with maximum priority
       if((left < size) && (data[left] > data[max]))
           max = left;
       if((right < size) && (data[right] > data[max]))
           max = right;
       // if index of maximum priority is not index, swap the index and max elements and call the method with max as its index
       if(max != index)
       {
           int temp = data[max];
           data[max] = data[index];
           data[index] = temp;
           bubbleDown(max);
       }
   }

   public int poll(){
       //Returns the node with the highest priority. This method should NOT remove that node
       if(size > 0)
           return data[0];
       return -1;
   }
  
   private void heapify(List<Integer> data){
       //implement the heapify method that will build a PQ given a list of data
      
       // create data of capacity
       this.data = new int[capacity];
       size = 0; // set size to 0
      
       // loop to insert the elements from data list
       for(int i=0;i<data.size();i++)
       {
           insert(data.get(i));
       }
   }
  
   public List<Integer> toSortedList(){
       //this method will return a list of all the integers in the priority queue in sorted order (Max Heap)
       //this method will remove all the data from the pq
       List<Integer> sorted = new ArrayList<Integer>();
      
       // loop that continues till there are elements in the list
       while(size > 0)
       {
           sorted.add(poll()); //add the current top priority element to the list
           remove(); // remove the current top priority element
       }
      
       return sorted;
   }
}

//end of PQ.java

// PQAssignment.java

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class PQAssignment {

   public static void main(String[] args) {

       List<Integer> list = randomList(20);
       System.out.println("Unsorted Input List: " + list.toString());
       PQ priorityQueue = new PQ(list);
       List<Integer> sortedList = priorityQueue.toSortedList();
       System.out.println("Sorted List Descending order: " + sortedList.toString());

   }

   private static List<Integer> randomList(int size){

       final Random rng = new Random();

       List<Integer> list = new ArrayList<>(size);

       for(int i = 0; i< size; i++){

       list.add(rng.nextInt()%10);

       }

       return list;

   }
}

//end of PQAssignment.java

Output:


Related Solutions

C++ Program 1–Implement a Priority Queue(PQ) using an UNSORTED LIST. Use an array size of 10...
C++ Program 1–Implement a Priority Queue(PQ) using an UNSORTED LIST. Use an array size of 10 elements. Use a circular array: Next index after last index is 0. Add the new node to next available index in the array. When you add an element, add 1 to index (hit max index, go to index 0). Test if array in full before you add. When you remove an element, from the list, move the following elements to the left to fill...
The following program is used to sum arrays. Fill in blanks of the following program to...
The following program is used to sum arrays. Fill in blanks of the following program to complete the program and make the output is: s = 150. #include <iostream.h> class Arr { int *a,n; public: Arr():a(0),n(0){} Arr(int *aa, int nn) {n=nn; a=new int [n]; for(int i=0;i<nn;i++) *(a+i)=*(aa+i); } ~Arr(){delete a;} _____________ {return *(a+i);} }; void main() { int b [5]={10,20,30,40,50}; Arr a1(b,5); int i=0,s=0; _____________ s+=a1.GetValue(i); cout<<"s="<<s<<endl; }
Given the following distribution, provide the following (i.e., fill in the blanks):
Given the following distribution, provide the following (i.e., fill in the blanks):X    P(x)    P(≤ X) Most Frequently Occurring Value _________6    0.25    _______ Expected Value of X _________8    0.45    _______ Standard Deviation of X _________12    0.30    ________ P(X > 6) _________
Implement a Priority Queue (PQ) using an UNSORTED LIST. Use an array size of 10 elements....
Implement a Priority Queue (PQ) using an UNSORTED LIST. Use an array size of 10 elements. Use a circular array: Next index after last index is 0. Add the new node to next available index in the array. When you add an element, add 1 to index (hit max index, go to index 0). Test if array in full before you add. When you remove an element, from the list, move the following elements to the left to fill in...
Fill in the blanks: Consider the following equilibrium and fill in the blanks with either increase...
Fill in the blanks: Consider the following equilibrium and fill in the blanks with either increase or decrease. I2(s) + 5F2(g) ⇌ 2IF5(g) A decrease in volume results in a Blank 1 in pressure which will Blank 2 the amount of IF5.
1 .RuntimeException class is a subclass of the Exception class. Fill in the blanks to complete...
1 .RuntimeException class is a subclass of the Exception class. Fill in the blanks to complete the declaration of the RuntimeException class. _____________   ________________    _________________ . . . 3. RuntimeException is a subclass of Exception. The constructor RuntimeException(String message) calls the parent class's constructor with the message argument. Which of the following makes the call correctly? this(message); super(message); super.Exception(message); Exception(message); 4. RuntimeException has overloaded constructors: the 1-argument constructor RuntimeException(String message) and the 2-argument constructor RuntimeException(String message, Throwable cause). The 2-argument...
Fill in the blanks on the following table
 Fill in the blanks on the following tableE&pshareholder basisdistributiondividendreturn of capitalcapital gain20,000300,00080,000120,00010,000170,000220,000100,000170,00020,000080,000<20,000>50,000170,000
Why is MgCO3 more soluble? Fill in the blanks with the given list of the following...
Why is MgCO3 more soluble? Fill in the blanks with the given list of the following words: base / a basic / acid / an acidic / a neutral / salt MgCO3 will be more soluble in an acidic solution than PbBr2 because the CO32- ion is___________ anion, whereas Br- is the conjugate __________ of a strong ________ (HBr) and therefore has ____________ pH.
write C program to implement the priority queue with the operation insert
write C program to implement the priority queue with the operation insert
Fill in the blanks in each of the following statements
Fill in the blanks in each of the following statementsa) --------- allows you to build JavaFx GUIS using drag and drop techniques.b) The elements in the scene graph are called --------------c) A(n) ----------- file contains the description of a JavaFX GUI.d) The method ---------------- is called by FMXLLoader before the GUI is displayed
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT