Question

In: Computer Science

(Generic PriorityQueue using Comparator) Revise MyPriorityQueue in Listing 24.8, using a generic parameter for comparing objects....

(Generic PriorityQueue using Comparator) Revise MyPriorityQueue in Listing 24.8, using a generic parameter for comparing objects. Define a new constructor with a Comparator as its argument as follows: PriorityQueue(Comparator comparator).

Solutions

Expert Solution

import java.util.Comparator;

public class Exercise06 {

 public static void main(String[] args) {
  Patient patient1 = new Patient("John", 2);
  Patient patient2 = new Patient("Jim", 1);
  Patient patient3 = new Patient("Tim", 5);
  Patient patient4 = new Patient("Cindy", 7);

  MyPriorityQueue<Patient> priorityQueue = new MyPriorityQueue<Patient>(new PatientComparator());
  priorityQueue.enqueue(patient1);
  priorityQueue.enqueue(patient2);
  priorityQueue.enqueue(patient3);
  priorityQueue.enqueue(patient4);

  while (priorityQueue.getSize() > 0)
   System.out.print(priorityQueue.dequeue() + " ");
 }
static class Patient implements Comparable<Patient> {
  private String name;
  private int priority;

  public Patient(String name, int priority) {
   this.name = name;
   this.priority = priority;
  }

  @Override
  public String toString() {
   return name + "(priority:" + priority + ")";
  }

  public int compareTo(Patient o) {
   return this.priority - o.priority;
  }
 }
static class PatientComparator implements Comparator<Patient> {
  @Override
  public int compare(Patient o1, Patient o2) {
   return o1.priority - o2.priority;
  }
 }

 static class MyPriorityQueue<E> {
  private Heap<E> heap;

  MyPriorityQueue(Comparator<? super E> comparator) {
   heap = new Heap<E>(comparator);
  }
public void enqueue(E newObject) {
   heap.add(newObject);
  }

  public E dequeue() {
   return heap.remove();
  }

  public int getSize() {
   return heap.getSize();
  }
 }

 static class Heap<E> {
  private java.util.ArrayList<E> list = new java.util.ArrayList<E>();
  private Comparator<? super E> comparator;

  /** Create a default heap */
  public Heap(Comparator<? super E> comparator) {
   this.comparator = comparator;
  }
/** Create a heap from an array of objects */
  public Heap(E[] objects, Comparator<? super E> comparator) {
   this.comparator = comparator;
   for (int i = 0; i < objects.length; i++)
    add(objects[i]);
  }
/** Add a new object into the heap */
  public void add(E newObject) {
   list.add(newObject); // Append to the heap
   int currentIndex = list.size() - 1; // The index of the last node

   while (currentIndex > 0) {
    int parentIndex = (currentIndex - 1) / 2;
    // Swap if the current object is greater than its parent
    if (comparator.compare(list.get(currentIndex), list.get(parentIndex)) > 0) {
     E temp = list.get(currentIndex);
     list.set(currentIndex, list.get(parentIndex));
     list.set(parentIndex, temp);
    } else
     break; // the tree is a heap now

    currentIndex = parentIndex;
   }
  }
/** Remove the root from the heap */
  public E remove() {
   if (list.size() == 0)
    return null;

   E removedObject = list.get(0);
   list.set(0, list.get(list.size() - 1));
   list.remove(list.size() - 1);
int currentIndex = 0;
   while (currentIndex < list.size()) {
    int leftChildIndex = 2 * currentIndex + 1;
    int rightChildIndex = 2 * currentIndex + 2;

    // Find the maximum between two children
    if (leftChildIndex >= list.size())
     break; // The tree is a heap
    int maxIndex = leftChildIndex;
    if (rightChildIndex < list.size()) {
     if (comparator.compare(list.get(maxIndex), list.get(rightChildIndex)) < 0) {
      maxIndex = rightChildIndex;
     }
    }

    // Swap if the current node is less than the maximum
    if (comparator.compare(list.get(currentIndex), list.get(maxIndex)) < 0) {
     E temp = list.get(maxIndex);
     list.set(maxIndex, list.get(currentIndex));
     list.set(currentIndex, temp);
     currentIndex = maxIndex;
    } else
     break; // The tree is a heap
   }
return removedObject;
  }

  /** Get the number of nodes in the tree */
  public int getSize() {
   return list.size();
  }
 }

}

Related Solutions

Revise this code to handle exceptions and provide correct total number of valid objects. (1) /**...
Revise this code to handle exceptions and provide correct total number of valid objects. (1) /** * class: CircleWithException * description: This program creates CircleWithException specification by using an instance variable/data/attribute named * radius. * Then, also we will create a static variable named numberOfObjects to count number of object when you create in a tester program. * In this program, you will learn how you declare an exception and define the exception. * This is a part of checked...
Revise this code to handle exceptions and provide correct total number of valid objects. (1) /**...
Revise this code to handle exceptions and provide correct total number of valid objects. (1) /** * class: CircleWithException * description: This program creates CircleWithException specification by using an instance variable/data/attribute named * radius. * Then, also we will create a static variable named numberOfObjects to count number of object when you create in a tester program. * In this program, you will learn how you declare an exception and define the exception. * This is a part of checked...
Revise this code to handle exceptions and provide correct total number of valid objects. (1) /**...
Revise this code to handle exceptions and provide correct total number of valid objects. (1) /** * class: CircleWithException * description: This program creates CircleWithException specification by using an instance variable/data/attribute named * radius. * Then, also we will create a static variable named numberOfObjects to count number of object when you create in a tester program. * In this program, you will learn how you declare an exception and define the exception. * This is a part of checked...
Design and build objects to be used by a real estate company for listing the properties for sale.
Design and build objects to be used by a real estate company for listing the properties for sale. A base object of a property is necessary. Decide what common about all properties and include these in the property object. Different type of properties are land, commercial and residential. A residential property can be single family and multi family. A commercial can be a commercial can be either a farm or non-farm.Look at real estate websites and decide what to include...
python Write a function pack_to_5(words) that takes a list of string objects as a parameter and...
python Write a function pack_to_5(words) that takes a list of string objects as a parameter and returns a new list containing each string in the title-case version. Any strings that have less than 5 characters needs to be expanded with the appropriate number of space characters to make them exactly 5 characters long. For example, consider the following list: words = ['Right', 'SAID', 'jO'] The new list would be: ['Right', 'Said ', 'Jo '] Since the second element only contains...
In C++: In this lab we will creating twos arrays of Generic objects, searching through those...
In C++: In this lab we will creating twos arrays of Generic objects, searching through those arrays using BINARY and SEQUENTIAL sorts, calculate the run-time of each method, and determine the BIG O, OMEGA and THETA notation. In our object we should have some way to compare elements to determine if one element is LESS THAN, GREATER THAN, and EQUAL TO. After this Generic Class is defined with a method that allows for comparison is completed, then you will create...
Comparing Objects Vs Comparing Primitive data Types Topic: Discuss how do we compare Strings for equality?...
Comparing Objects Vs Comparing Primitive data Types Topic: Discuss how do we compare Strings for equality? Provide coding examples. How String comparison is different than the primitive data type comparison? Please cite any resources you used.
Overview In this assignment you are required to implement binary code comparator using Xilinx that it...
Overview In this assignment you are required to implement binary code comparator using Xilinx that it is compatible with the MXK Seven Segment Displays. You will draw your digital logic circuit using Xilinx and then simulate it to verify the functionality of your design. Software Requirements ? Xilinx ISE 10.1 or higher Specifications Binary Code Comparator The binary code comparator is to be implemented and made compatible with the seven 7-segment displays of the board. Represent the first five digits...
build in multisim ,circuit using window comparator that works to turn on a green LED and...
build in multisim ,circuit using window comparator that works to turn on a green LED and red LED is off .when the dc input voltage is between 360mv-380mv and when the input is above or below this range red LED is on and green LED is off.
implement c++ Quicksort using median of 3 as pivot. this also pass comparator as a function...
implement c++ Quicksort using median of 3 as pivot. this also pass comparator as a function param so it can sort vector in increasing or decreasing order based on the comparator passed. the test code uses std::less comparator. #ifndef QSORT_H #define QSORT_H #include #include using namespace std; template T median_of_three(T& a, T& b, T& c, TComparator comparator) { } template size_t partition(vector& vec, TComparator& comparator, size_t low, size_t high) { // TODO: implement. } template void QuickSort(vector& vec, TComparator comparator,size_t...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT