Question

import java.util.Scanner; import class17.HeapPriorityQueue; import class17.PriorityQueue; /*************** * Homework D * * * Remove any initial...

import java.util.Scanner;

import class17.HeapPriorityQueue;
import class17.PriorityQueue;

/***************
* Homework D
*
*
* Remove any initial package declaration that might be added to your file in
* case you edit it in eclipse.
*
* The goal of the homework is to create two ArrayList based implementations of
* a Priority Queue as explained in Section 9.2 (in 9.2.4 and 9.2.5) of the
* textbook.
*
* These are to be made by completing the classes PQunsorted and PQsorted as
* given below. In completing these classes you should only use the instance
* members array, capacity and size, but you should add implementations for the
* required Priority Queue methods. Only change their methods as indicated by
* TODO instructions
*
* Finally, you should make the main program display your name and 8 digit ID
* number.
*
* Your implementations should work interchangeably with the heap based version.
* The main program runs both your implementations and the (correct) heap based
* one from class at once. When your code is correct, it should produce any
* output three times over.
********************************************************************/

class PQunsorted<K extends Comparable<K>> implements PriorityQueue<K> {
K[] data;
int size;
int capacity;

public PQunsorted() {
  capacity = 100;
  size = 0;
  data = (K[]) new Comparable[capacity];
}

// easy insertion
public void insert(K x) throws Exception {
  if (size >= capacity) throw new Exception("Queue full");
  data[size++] = x;
}

public K removeMin() throws Exception {
  // TODO complete code to remove min here
  return null;
}
}

class PQsorted<K extends Comparable<K>> implements PriorityQueue<K> {
K[] data;
int size;
int capacity;

public PQsorted() {
  capacity = 100;
  size = 0;
  data = (K[]) new Comparable[capacity];
}
public void insert(K x) throws Exception {
  // TODO complete code to insert x, keeping the array sorted so the min is at the end

}

        // easy removal in this implementation
public K removeMin() throws Exception {
  if (size == 0) throw new Exception("Queue Empty");
  return data[--size];
}
}

// ---------------------- main program to test implementations ---

class D00000000 {
public static void main(String args[]) {
  PriorityQueue<String> pq = new HeapPriorityQueue<>();
  PriorityQueue<String> pqU = new PQunsorted<>();
  PriorityQueue<String> pqS = new PQsorted<>();
  boolean done = false;
  Scanner sc = new Scanner(System.in);
  while (!done) {
   try {
    // add your name into the following print statement
    System.out.println(
                                  "\nProgram by: xxxx ---- cmds are + - Q: >>");
    String cmd = sc.next();
    String entry = null;
    char command = cmd.charAt(0);
    if (command == '+')
     entry = sc.next();
    switch (cmd.charAt(0)) {
    case 'Q':
     done = true;
     break;
    case '+':
     pq.insert(entry);
     pqU.insert(entry);
     pqS.insert(entry);
     break;
    case '-':
     System.out.print(pq.removeMin() + " ");
     System.out.print(pqU.removeMin() + " ");
     System.out.print(pqS.removeMin() + "\n");
     break;
    }
   } catch (Exception e) {
    System.out.println("Error " + e.toString());
   }
  }
  sc.close();
}

//PriorityQueue

package class17;

public interface PriorityQueue<K extends Comparable<K>> {
   public void insert(K x) throws Exception;
   public K removeMin() throws Exception;
}

//HeapPriorityQueue

package class17;

import java.util.Iterator;

public class HeapPriorityQueue<K extends Comparable<K>> implements
      PriorityQueue<K> {
   private K data[];
   private int size;
   private int capacity;

   // constructors
   public HeapPriorityQueue() {
      capacity = 100;
      size = 0;
      data = (K[]) new Comparable[capacity];
   }

   public HeapPriorityQueue(int c) {
      capacity = c;
      size = 0;
      data = (K[]) new Comparable[capacity];
   }

   // required priority queue methods
   public void insert(K x) throws Exception {
      if (size >= capacity - 1)
         throw new Exception("Priority Queue Full");
      data[size++] = x;
      bubbleUp(size - 1);
   }

   public K removeMin() throws Exception {
      if (size <= 0)
         throw new Exception("Priority Queue Empty");
      swapData(0, --size);
      bubbleDown(0);
      return data[size];
   }

   // auxiliary utility methods
   private void swapData(int n, int m) {
      K temp = data[n];
      data[n] = data[m];
      data[m] = temp;
   }

   private void bubbleUp(int n) {
      if (n <= 0)
         return; // at root
      K dn = data[n];
      K dp = data[(n - 1) / 2]; // parent data
      if (dn.compareTo(dp) >= 0)
         return; // no problems
      swapData(n, (n - 1) / 2);
      bubbleUp((n - 1) / 2);
   }

   public void bubbleDown(int n) {
      if (2 * n + 1 >= size)
         return; // at leaf
      K dn = data[n];
      K dl = data[2 * n + 1]; // left child
      K dr = dl;
      if (2 * n + 2 < size)
         dr = data[2 * n + 2]; // right child
      if (dn.compareTo(dl) < 0&& dn.compareTo(dr) < 0)
         return; // no problems
      if (dr.compareTo(dl) < 0) {
         swapData(n, 2 * n + 2);
         bubbleDown(2 * n + 2);
      } else {
         swapData(n, 2 * n + 1);
         bubbleDown(2 * n + 1);
      }
   }

   // heap creation
   public void heapify(Iterator<K> x) throws Exception {
      while (x.hasNext()) {
         if (size + 1 == capacity)
            break;
         data[size++] = x.next();
      }
      int n = size / 2;
      while (--n >= 0)
         bubbleDown(n);
      if (x.hasNext())
         throw new Exception("Heap is Full");
   }

}

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

the code is correct

import java.util.Scanner;

import class17.HeapPriorityQueue;
import class17.PriorityQueue;
******************************************************************/
class PQunsorted<K extends Comparable<K>> implements PriorityQueue<K> {
K[] data;
int size;
int capacity;
public PQunsorted() {
capacity = 100;
size = 0;
data = (K[]) new Comparable[capacity];
}

// easy insertion
public void insert(K x) throws Exception {
if (size >= capacity) throw new Exception("Queue full");
data[size++] = x;
}
public K removeMin() throws Exception {
// TODO complete code to remove min here
return null;
}
}
class PQsorted<K extends Comparable<K>> implements PriorityQueue<K> {
K[] data;
int size;
int capacity;
public PQsorted() {
capacity = 100;
size = 0;
data = (K[]) new Comparable[capacity];
}
public void insert(K x) throws Exception {
// TODO complete code to insert x, keeping the array sorted so the min is at the end
}
// easy removal in this implementation
public K removeMin() throws Exception {
if (size == 0) throw new Exception("Queue Empty");
return data[--size];
}
}
// ---------------------- main program to test implementations ---
class D00000000 {
public static void main(String args[]) {
PriorityQueue<String> pq = new HeapPriorityQueue<>();
PriorityQueue<String> pqU = new PQunsorted<>();
PriorityQueue<String> pqS = new PQsorted<>();
boolean done = false;
Scanner sc = new Scanner(System.in);
while (!done) {
try {
// add your name into the following print statement
System.out.println(
"\nProgram by: xxxx ---- cmds are + - Q: >>");
String cmd = sc.next();
String entry = null;
char command = cmd.charAt(0);
if (command == '+')
entry = sc.next();
switch (cmd.charAt(0)) {
case 'Q':
done = true;
break;
case '+':
pq.insert(entry);
pqU.insert(entry);
pqS.insert(entry);
break;
case '-':
System.out.print(pq.removeMin() + " ");
System.out.print(pqU.removeMin() + " ");
System.out.print(pqS.removeMin() + "\n");
break;
}
} catch (Exception e) {
System.out.println("Error " + e.toString());
}
}
sc.close();
}
//PriorityQueue
package class17;
public interface PriorityQueue<K extends Comparable<K>> {
public void insert(K x) throws Exception;
public K removeMin() throws Exception;
}
//HeapPriorityQueue
package class17;
import java.util.Iterator;
public class HeapPriorityQueue<K extends Comparable<K>> implements
PriorityQueue<K> {
private K data[];
private int size;
private int capacity;
// constructors
public HeapPriorityQueue() {
capacity = 100;
size = 0;
data = (K[]) new Comparable[capacity];
}
public HeapPriorityQueue(int c) {
capacity = c;
size = 0;
data = (K[]) new Comparable[capacity];
}
// required priority queue methods
public void insert(K x) throws Exception {
if (size >= capacity - 1)
throw new Exception("Priority Queue Full");
data[size++] = x;
bubbleUp(size - 1);
}
public K removeMin() throws Exception {
if (size <= 0)
throw new Exception("Priority Queue Empty");
swapData(0, --size);
bubbleDown(0);
return data[size];
}
// auxiliary utility methods
private void swapData(int n, int m) {
K temp = data[n];
data[n] = data[m];
data[m] = temp;
}
private void bubbleUp(int n) {
if (n <= 0)
return; // at root
K dn = data[n];
K dp = data[(n - 1) / 2]; // parent data
if (dn.compareTo(dp) >= 0)
return; // no problems
swapData(n, (n - 1) / 2);
bubbleUp((n - 1) / 2);
}
public void bubbleDown(int n) {
if (2 * n + 1 >= size)
return; // at leaf
K dn = data[n];
K dl = data[2 * n + 1]; // left child
K dr = dl;
if (2 * n + 2 < size)
dr = data[2 * n + 2]; // right child
if (dn.compareTo(dl) < 0&& dn.compareTo(dr) < 0)
return; // no problems
if (dr.compareTo(dl) < 0) {
swapData(n, 2 * n + 2);
bubbleDown(2 * n + 2);
} else {
swapData(n, 2 * n + 1);
bubbleDown(2 * n + 1);
}
}
// heap creation
public void heapify(Iterator<K> x) throws Exception {
while (x.hasNext()) {
if (size + 1 == capacity)
break;
data[size++] = x.next();
}
int n = size / 2;
while (--n >= 0)
bubbleDown(n);
if (x.hasNext())
throw new Exception("Heap is Full");
}
}

Add a comment
Know the answer?
Add Answer to:
import java.util.Scanner; import class17.HeapPriorityQueue; import class17.PriorityQueue; /*************** * Homework D * * * Remove any initial...
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
  • java The following code is an implementation of a HeapPriorityQueue. You are to implement the methods...

    java The following code is an implementation of a HeapPriorityQueue. You are to implement the methods commented with: // TODO: TIP: Do not just go from memory of your assignment implementation, be sure to consider carefully the constructor and method implementation provided to you. NOTE: You do not have to provide an implementation for any methods intentionally omitted public class Heap PriorityQueue implements PriorityQueue private final static int DEFAULT SIZE 10000 private Comparable [ ] storage private int currentSize: public...

  • 2. Write MinheapPriorityQueue constructor, which takes an array of data, and construct the max heap priority...

    2. Write MinheapPriorityQueue constructor, which takes an array of data, and construct the max heap priority queue using bottom-up algorithm. The expected run time should be O(n), where n is the total number of data. BubbleDown method is provided. You may test it in this minHeap public class MinHeapPriorityQueue<E extends Comparable<? super E>>{ private E data[]; private int size; public MinHeapPriorityQueue(){ this(100); } public MinHeapPriorityQueue(int cap){ size = 0; data = (E[]) new Comparable[cap]; } public MinHeapPriorityQueue(int[] a){ } public...

  • Write a second constructor that could be added to the HeapPriorityQueue class. This constructor accepts an...

    Write a second constructor that could be added to the HeapPriorityQueue class. This constructor accepts an array of elements as a parameter and uses that array as the heap rather than creating a new array. Of course, the array passed in is probably not in proper heap ordering, so you must rearrange it until it is. There's a neat trick for achieving this: If you just "bubble down" all of the non-leaf nodes of the heap, starting from the last...

  • package algs24; import stdlib.StdIn; import stdlib.StdOut; /** * The <tt>PtrHeap</tt> class is the priorityQ class from...

    package algs24; import stdlib.StdIn; import stdlib.StdOut; /** * The <tt>PtrHeap</tt> class is the priorityQ class from Question 2.4.24. * It represents a priority queue of generic keys. *   * It supports the usual <em>insert</em> and <em>delete-the-maximum</em> * operations, along with methods for peeking at the maximum key, * testing if the priority queue is empty, and iterating through * the keys. * For additional documentation, see <a href="http://algs4.cs.princeton.edu/24pq">Section 2.4</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne....

  • Write a second constructor that could be added to the HeapPriorityQueue class. This constructor accepts an...

    Write a second constructor that could be added to the HeapPriorityQueue class. This constructor accepts an array of elements as a parameter and uses that array as the heap rather than creating a new array. Of course, the array passed in is probably not in proper heap ordering, so you must rearrange it until it is. There's a neat trick for achieving this: If you just "bubble down" all of the non-leaf nodes of the heap, starting from the last...

  • I am not passing some of the code when i run the testing . PriorityQueue public...

    I am not passing some of the code when i run the testing . PriorityQueue public class PriorityQueue<T extends Comparable<T>> implements IPriorityQueue<T> {    private Vector<T> theVector = new Vector<>(0, 1);    private int size = 0;    @Override    public void insert(T element) {        theVector.pushBack(element);        size++;        bubbleUp(); }    @Override    public T peekTop() throws java.util.NoSuchElementException {        if (isEmpty()) {            throw new java.util.NoSuchElementException();        }       ...

  • I need some help with some homework questions. How would I implement the to-do's? ----------------------------------------------------------------------------------------------------------------------------------------------------------- AbstractArrayHea

    I need some help with some homework questions. How would I implement the to-do's? ----------------------------------------------------------------------------------------------------------------------------------------------------------- AbstractArrayHeap.Java package structures; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.NoSuchElementException; public abstract class AbstractArrayHeap<P, V> {   protected final ArrayList<Entry<P, V>> heap;   protected final Comparator<P> comparator; protected AbstractArrayHeap(Comparator<P> comparator) {     if (comparator == null) {       throw new NullPointerException();     }     this.comparator = comparator;     heap = new ArrayList<Entry<P, V>>();   } public final AbstractArrayHeap<P, V> add(P priority, V value) {     if (priority == null || value...

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

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

  • Priority Queue Demo import java.util.*; public class PriorityQueueDemo {    public static void main(String[] args) {...

    Priority Queue Demo import java.util.*; public class PriorityQueueDemo {    public static void main(String[] args) {        //TODO 1: Create a priority queue of Strings and assign it to variable queue1               //TODO 2: Add Oklahoma, Indiana, Georgia, Texas to queue1                      System.out.println("Priority queue using Comparable:");        //TODO 3: remove from queue1 all the strings one by one        // with the "smaller" strings (higher priority) ahead of "bigger"...

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