Question

Comparing the insertion and removing performance between ALPQueue with HeapPQueue. Requirements: 1/ Task1: implement a concrete...

Comparing the insertion and removing performance between ALPQueue with HeapPQueue. Requirements:

1/ Task1: implement a concrete ALPQueue class (an ArrayList based priority queue) that extends the AbstractPQueue discussed in the class, along with PQueue.java, ArrayList.java, List.java, PQEntry.java , EntryComparitor.java, and OutOfRangeException.java given in the class (any other implementation of above classes that are not compatible with List interface and AbstractPQueue class will not receive any credit).

2/ Task2: implement a concrete HeapPQueue class (a Heap based priority queue) that extends the AbstractPQueue discussed in the class. Similary, you also need PQueue.java, ArrayList.java, List.java, PQEntry.java , EntryComparitor.java, and OutOfRangeException.java given in the class. The ADT of HeapPQueue class is given below:

public class HeapPQueue extends AbstractPQueue {
  private ArrayList list = new ArrayList();

  //constructor: your implementation

  public int size();
  public boolean isEmpty();
  public void heapUp(int i);
  public void heapDown(int i);
  public PQEntry insert(Integer key, String value);
  public PQEntry removeMin();
  public PQEntry min();
}

3/ Task3: write a performance test program to measure the performance of the above two classes in running time. To do that, you may want to construct two big priority queue instances: one for ALPQueue and one for HeapPQueue. Perform at least 5,000 (random numbers) insert() operations and 5,000 removeMin() operation for each priority queue. The procedure of your test program should be the following:

1. construct an instance of ALPQueue with the capacity of 5,000 entries;

2. construct an instance of HeapPQueue with the capacity of 5,000 entries;

3. construct an integer array with the capacity of 5,000 integers, then fill the array with 5,000 random integers (as the potential key values);

3. record the system time Ta_insert_before;

4. insert 5,000 data items into the ALPQueue instance (the keys are coming from the integer array, and their correponding values can be a String, e.g., CIS + key_value;

5. record the system time Ta_insert_after;

6. compute the insertion time consumption of the ALPQueue;

7. repeat steps 3-6 to remove 5,000 entries, and compute the removal time consumption;

8. repeat 3-7 for the instance of HeapPQueue;

9. print out the results

Your test program should print out the following information:

ALPQueue:

insert 5000 entries: xxx ms

remove 5000 entries: xxx ms

HeapPQueue:

insert 5000 entries: xxx ms

remove 5000 entries: xxx ms

Find below java classes provided by the instructor in class that go along with the assignment:

a) PQueue.java class:

public interface PQueue {
int size();
boolean isEmpty();
PQEntry min();
PQEntry removeMin();
PQEntry insert (Integer k, String v);
}
b) PQEntry.java class:

public class PQEntry {
   private Integer key;

   private String value;

   public PQEntry(Integer k, String v) {

   key = k;

   value = v;
   }
public PQEntry() {
   this(-1, null);
}
public Integer getKey() {

return key;
}
public String getValue() {

return value;
}
public void setKey(Integer k) {
key = k;
}
public void setValue(String v) {
value = v;
}
}

c) EntryComparator.java class:

import java.util.Comparator;
public class EntryComparator implements Comparator {
   public int compare(Object a, Object b) {

   int akey = ((PQEntry)a).getKey();

   int bkey = ((PQEntry)b).getKey();

   return akey - bkey;
   }
}

d) AbstractPQueue.java class:

public abstract class AbstractPQueue implements PQueue {
   private EntryComparator comp;

   protected AbstractPQueue() {

   this(new EntryComparator());

   }

   protected AbstractPQueue(EntryComparator c) {comp = c;}

   protected int compare (PQEntry a, PQEntry b) {

   return comp.compare(a,b);
   }
   public boolean isEmpty(){return size() == 0;}

}

e) ALPQueue.java class:

public class ALPQueue extends AbstractPQueue {
   private List list = new ArrayList();

   public ALPQueue() {super();}

   public ALPQueue (EntryComparator com) { super(com);}

   public int size() { return list.size();}
   public PQEntry insert (Integer k, String v) {
       PQEntry newest = new PQEntry (k,v);
   try {
       list.add(list.size(), newest);}

   catch (OutOfRangeException e) {

   System.out.println("Out of Range");
   }
   return newest;
   }
   private int findMin() {

       int min = 0;

       if(list.size() == 1) return min;

       try {

       for(int i = 1; i < list.size(); i++) {

       if(compare((PQEntry) list.get(min), (PQEntry) list.get(i)) > 0)

       min = i;
       }
       }
       catch (OutOfRangeException ex) {

       System.out.println("Out of Range");
       }
       return min;

       }
       public PQEntry min() {

           if(isEmpty()) {return null;}

           PQEntry en = null;

           try {

           en = (PQEntry) list.get(findMin());

           } catch (OutOfRangeException e) {

           System.out.println("Out of Range");

           } return en;

           }

           public PQEntry removeMin() {

           if(isEmpty()) {return null;}

           PQEntry en = null;

           try {

           en = (PQEntry) list.remove(findMin());}
           catch (OutOfRangeException e) {

           System.out.println("Out of Range");

           } return en;

}

}

f) List.java class:

public interface List {
   public int size();

   public boolean isEmpty();

   public Object get(int i) throws OutOfRangeException;

   public void set(int i, Object e) throws OutOfRangeException;

   public void add(int i, Object e) throws OutOfRangeException;

   public Object remove(int i) throws OutOfRangeException;

   }

g) OutOfRangeException.java class:

public class OutOfRangeException extends Exception {
   public OutOfRangeException(String str){
       System.out.println("OutOfRangeException:" + str);}
       public OutOfRangeException (){
       this("Out Of Range");}
  
}

h) ArrayList.java class:

public class ArrayList implements List {
   private int CAP;
   private int size;
   private Object[] item;
   public ArrayList(int capacity){
       this.size = 0;
       this.CAP = capacity;
       this.item = new Object [capacity];
   }
   public ArrayList () {
       this(100);
   }
   public int size(){
       return size;
       }
       public boolean isEmpty(){
       return size==0;
       }
       public Object get(int i) throws OutOfRangeException {
       if (i<0 || i>=size)
           throw new OutOfRangeException ("Out of Range");
       return item [i];
       }
       public void set(int i, Object e) throws OutOfRangeException {
           if (i<0 || i>=size)
               throw new OutOfRangeException ("Out of Range");
           item [i] = e;
       }
       public void add(int i, Object e) throws OutOfRangeException {
           if (i<0 || i>size)
               throw new OutOfRangeException ("Out of Range");
           for (int j = size - 1; j>=i; j--)
               item[j+1] = item [j];
           size++;
       }
       public Object remove(int i) throws OutOfRangeException {
           if (i<0 || i>=size)
               throw new OutOfRangeException ("Out of Range");
           Object answer = item[i];
           for (int j=i; j<size-1; j++)
               item[j] = item[j+1];
           item[size-1] = null;
           size--;
           return answer;
       }
}
Hope it's clear now!

0 0
Add a comment Improve this question Transcribed image text
Answer #1

// Java progrm to demonstrate working of priority queue in Java
import java.util.*;

class Example
{
   public static void main(String args[])
   {
       // Creating empty priority queue
       PriorityQueue<String> prioirty_queue =
                       new PriorityQueue<String>();

       // Adding items to the prioirty_queue using add()
       prioirty_queue.add("C");
       prioirty_queue.add("C++");
       prioirty_queue.add("Java");
       prioirty_queue.add("Python");

       // Printing the most priority element
       System.out.println("Head value using peek function:"
                                       + prioirty_queue.peek());
  
System.out.println("For Array Queue Execution Time:");
//divide by 1000000 to get milliseconds.
System.out.print("Time for 5000 insertions ::");
long startTime = System.nanoTime();
  
  
       for (int i = 1;i<5000 ; i++)
       prioirty_queue.add("Python");
      
   long endTime = System.nanoTime();
   long duration = (endTime - startTime);
   System.out.println(duration);
     
   System.out.print("\nTime for 5000 Deletions ::");
   long startTime1 = System.nanoTime();      
   for (int i = 1;i<5000 ; i++)
       prioirty_queue.poll();
long endTime1 = System.nanoTime();
long duration1 = (endTime1 - startTime1);
   System.out.println(duration1);
           // Removing the top priority element (or head) and
       // printing the modified prioirty_queue using poll()
  


   }
}

/**
* Created with IntelliJ IDEA.
* Implement a priority queue using a heap
* The heap is implemented using an array indexed from 1
*/
public class Heap_priority_Queue<T extends Comparable<T>> {
T[] arr;
int N;

public static void main(String[] args) {
Heap_priority_Queue<Integer> pq = new Heap_priority_Queue<Integer>();


System.out.println("For Heap Queue Execution Time:");
//divide by 1000000 to get milliseconds.
System.out.print("Time for 5000 insertions ::");
long startTime = System.nanoTime();
       for (int i = 1;i<5000 ; i++)
       pq.insert(i);
   long endTime = System.nanoTime();
   long duration = (endTime - startTime);
   System.out.println(duration);
     
     
   System.out.print("\nTime for 5000 Deletions ::");
   long startTime1 = System.nanoTime();
   for (int i = 1;i<5000 ; i++)
       pq.delMax();   
long endTime1 = System.nanoTime();
long duration1 = (endTime1 - startTime1);
   System.out.println(duration1);
  
}

public Heap_priority_Queue(){
arr = (T[]) new Comparable[2];
N = 0;
}

public void insert(T t){
if (N == arr.length - 1) resize(2*N + 1);
arr[++N] = t;
swim(N);
}

public T delMax(){
if (isEmpty()) return null;
T t= arr[1];
exchanger(1,N--);
arr[N+1] = null;
sink(1);

//resize this array
if (N == (arr.length -1)/4) resize((arr.length-1) / 2 + 1);
return t;
}
//helper methods
public String toString(){
StringBuffer sb = new StringBuffer();
for(int i = 1; i <= N; i ++)
sb.append(arr[i].toString()+" ");
return sb.toString();
}

private boolean isEmpty(){
return N == 0;
}
private void resize(int capacity){
T[] copy = (T[]) new Comparable[capacity];
for(int i = 1; i <= N; i ++ )
copy[i] = arr[i];
arr = copy;
}

private void swim(int k){
while(k > 1 && _least(k/2, k)){
exchanger(k/2,k);
k = k/2;
}
}

private void sink(int k){
while (2*k < N){
int j = 2 * k;
if(j < N && _least(j, j +1)) j = j + 1;
if(_least(j, k)) break;
exchanger(k,j);
k = j;
}
}

private boolean _least(int i, int j){
if (arr[i].compareTo(arr[j]) < 0)
return true;
return false;
}

private void exchanger(int i, int j){
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}

COMMENT DOWN FOR ANY QUERIES,

AND LEAVE A THUMBS UP IF THIS ANSWER HELPS YOU.

Add a comment
Know the answer?
Add Answer to:
Comparing the insertion and removing performance between ALPQueue with HeapPQueue. Requirements: 1/ Task1: implement a concrete...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Comparing the insertion and removing performance between ALPQueue with HeapPQueue. Requirements: ...

    Comparing the insertion and removing performance between ALPQueue with HeapPQueue. Requirements: 1/ Task1: implement a concrete ALPQueue class (an ArrayList based priority queue) that extends the AbstractPQueue discussed in the class, along with PQueue.java, ArrayList.java, List.java, PQEntry.java , EntryComparitor.java, and OutOfRangeException.java given in the class (any other implementation of above classes that are not compatible with List interface and AbstractPQueue class will not receive any credit). 2/ Task2: implement a concrete HeapPQueue class (a Heap based priority queue) that extends...

  • Can anyone helps to create a Test.java for the following classes please? Where the Test.java will...

    Can anyone helps to create a Test.java for the following classes please? Where the Test.java will have a Scanner roster = new Scanner(new FileReader(“roster.txt”); will be needed in this main method to read the roster.txt. public interface List {    public int size();    public boolean isEmpty();    public Object get(int i) throws OutOfRangeException;    public void set(int i, Object e) throws OutOfRangeException;    public void add(int i, Object e) throws OutOfRangeException; public Object remove(int i) throws OutOfRangeException;    } public class ArrayList implements List {   ...

  • Complete an Array-Based implementation of the ADT List including a main method and show that the...

    Complete an Array-Based implementation of the ADT List including a main method and show that the ADT List works. Draw a class diagram of the ADT List __________________________________________ public interface IntegerListInterface{ public boolean isEmpty(); //Determines whether a list is empty. //Precondition: None. //Postcondition: Returns true if the list is empty, //otherwise returns false. //Throws: None. public int size(); // Determines the length of a list. // Precondition: None. // Postcondition: Returns the number of items in this IntegerList. //Throws: None....

  • What is wrong with my code, when I pass in 4 It will not run, without...

    What is wrong with my code, when I pass in 4 It will not run, without the 4 it will run, but throw and error. I am getting the error   required: no arguments found: int reason: actual and formal argument lists differ in length where T is a type-variable: T extends Object declared in class LinkedDropOutStack public class Help { /** * Program entry point for drop-out stack testing. * @param args Argument list. */ public static void main(String[] args)...

  • I was told I need three seperate files for these classes is there anyway to tie...

    I was told I need three seperate files for these classes is there anyway to tie all these programs together into one program after doing that. I'm using netbeans btw. import java.util.ArrayList; import java.util.Scanner; /** * * */ public class MySorts {       public static void main(String[] args) {             Scanner input = new Scanner(System.in);             String sentence;             String again;             do {                   System.out                               .println("Enter a sentence, I will tell you if it is a palindrome: ");...

  • Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to...

    Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to both classes: public void reverseThisList(), This method will reverse the lists. When testing the method: print out the original list, call the new method, then print out the list again ------------------------------------------------------------------------- //ARRAY LIST class: public class ArrayList<E> implements List<E> { /** Array of elements in this List. */ private E[] data; /** Number of elements currently in this List. */ private int size; /**...

  • Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,In...

    Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,Integer. Im not sure how to fix this. public class Evaluator { public static void evaluatePost(String postFix)    {        LinkedStack stack2 = new LinkedStack();        int val1;        int val2;        int result;        for(int i = 0; i < postFix.length(); i++)        {            char m = postFix.charAt(i);            if(Character.isDigit(m))            {                stack2.push(m);            }            else            {               ...

  • JAVA Implement a MyQueue class which implements a queue using two stacks. private int maxCapacity...

    JAVA Implement a MyQueue class which implements a queue using two stacks. private int maxCapacity = 4; private Stack stack1; private Stack stack2; Note: You can use library Stack but you are not allowed to use library Queue and any of its methods Your Queue should not accept null or empty String or space as an input You need to implement the following methods using two stacks (stack1 & stack2) and also you can add more methods as well: public...

  • I need to implement a stack array but the top of the stack has to be...

    I need to implement a stack array but the top of the stack has to be Initialize as the index of the last location in the array.    //Array implementation of stacks.    import java.util.Arrays;       public class ArrayStack implements Stack {        //Declare a class constant called DEFAULT_STACK_SIZE with the value 10.           private static final int DEFAULT_STACK_SIZE = 10;           /* Declare two instance variables:            1. An integer called...

  • // CMPS 390 // MinHeap.java // Complete 4 methods: getMin, add, removeMin, reheap public class MinHeap...

    // CMPS 390 // MinHeap.java // Complete 4 methods: getMin, add, removeMin, reheap public class MinHeap { private Comparable a heap; // array of heap entries private static final int DEFAULT MAX SIZE = 100; private int lastIndex; // index of last entry public MinHeap() { heap = new Comparable (DEFAULT_MAX_SIZE]; lastIndex = 0; } // end default constructor public MinHeap (int maxSize) { heap = new Comparable (maxSize); lastIndex = 0; } // end constructor public MinHeap (Comparable[] entries)...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT