Question

Q4. In class, we discussed the priority queue (PQ) ADT implemented using min-heap. In a min- heap, the element of the heap with the smallest key is the root of the binary tree. On the other hand, a max-heap has as root the element with the biggest key, and the relationship between the keys of a node and its parent is reversed of that of a min-heap. We also discussed an array-based implementation of heaps. In this assignment, your task is to implement your own flexible priority queue ADT using both min- and max-heap in Java. The specifications of the flexible priority queue are provided in the following. The heap (s) must be implemented from scratch using an array that is automatically extendable. You are not allowed to use any list (including arraylist, tree, vector. or heap implementation already available in Java. You must not duplicate code for implementing min- and max-heaps (i.e. the same code must be used for constructing min or max heaps. Hence think of a flexible way to parameterize ur code for either min- or max heap). The following are the access methods of the flexible priority queue ADT remove0: removes and returns the entry (a key, value pair) with the smallest or biggest key depending on the current state of the priority queue (either Min or Max)

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

Complete Program:

File: Entry.java

// Entry class implementation
public class Entry<K extends Comparable<K>, V extends Comparable<V>>
{  
   // data fields
   private K key;
   private V value;
  
   // default constructor implementation
   public Entry()
   {
       this(null, null);
   }
  
   // parameterized constructor implementation
   public Entry(K k, V v)
   {
       key = k;
       value = v;
   }
  
   // getKey method implementation
   public K getKey()
   {
       return key;
   }
  
   // getValue method implementation
   public V getValue()
   {
       return value;
   }
  
   // setKey method implementation
   public void setKey(K k)
   {
       key = k;
   }
  
   // setValue method implementation
   public void setValue(V v)
   {
       value = v;
   }
  
   // toString method implementation
   public String toString()
   {
       return "(" + key + ", " + value + ")";
   }
} // end of Entry class

File: FlexiblePriorityQueue.java

// FlexiblePriorityQueue class implementation
public class FlexiblePriorityQueue<K extends Comparable<K>, V extends Comparable<V>>
{
   // data fields
   private Entry<K, V>[] heap;
   private int numberOfEntries;
   private String currentState;
   private final String MIN_HEAP = "Min Heap";
   private final String MAX_HEAP = "Max Heap";

   // default constructor implementation
   @SuppressWarnings("unchecked")
   public FlexiblePriorityQueue()
   {
       heap = (Entry<K, V>[])new Entry[0];
       numberOfEntries = 0;      
       currentState = MIN_HEAP;
   } // end of default constructor

   // insert (k, v): Insert the (k, v) entry which is a key(k), value(v) pair to the priority queue.
   @SuppressWarnings("unchecked")
   public void insert(K k, V v)
   {      
       Entry<K, V>[] tempHeap = (Entry<K, V>[])new Entry[numberOfEntries + 1];
      
       for(int i = 0; i < numberOfEntries; i++)
       {
           tempHeap[i] = heap[i];
       }      
       heap = tempHeap;
      
       int count = numberOfEntries;
       int parent = (int) Math.floor((count - 1) / 2);
      
       if(currentState.equalsIgnoreCase(MIN_HEAP))
       {
           while(count > 0 && k.compareTo(heap[parent].getKey()) < 0)
           {
               heap[count] = heap[parent];
               count = parent;
               parent = (int) Math.floor((count - 1) / 2);
           }
       }
      
       if(currentState.equalsIgnoreCase(MAX_HEAP))
       {
           while(count > 0 && k.compareTo(heap[parent].getKey()) > 0)
           {
               heap[count] = heap[parent];
               count = parent;
               parent = (int) Math.floor((count - 1) / 2);
           }
       }
      
       heap[count] = new Entry<K, V>(k, v);;
       numberOfEntries++;
   } // end of insert method
  
   // remove(): removes and returns the entry (a key, value pair) with the smallest or biggest key depending on the current state of the priority queue (either Min or Max).
   public Entry<K, V> remove()
   {
       if(isEmpty())
           return null;

       Entry<K, V> topEntry = heap[0];
       heap[0] = heap[numberOfEntries - 1];
       numberOfEntries--;
       heapify(0);
      
       return topEntry;
   } // end of remove method
      
   // top(): returns the top entry (with the minimum or the maximum key depending on whether it is a Min- or Max-priority queue, without removing the entry.
   public Entry<K, V> top()
   {
       if(numberOfEntries == 0)
           return null;
       else
           return heap[0];
   } // end of top method

   // toggle() transforms a min- to a max-priority queue or vice versa.
   public void toggle()
   {
       if(currentState.equalsIgnoreCase(MIN_HEAP))
           currentState = MAX_HEAP;
       else
           currentState = MIN_HEAP;

       rebuildHeap();
   } // end of toggle method

   // switchToMin(): transforms a max- to a min-priority queue: else leave unchanged.
   public void switchToMin()
   {
       if(currentState.equalsIgnoreCase(MAX_HEAP))
       {
           currentState = MIN_HEAP;
           rebuildHeap();
       }
   } // end of switchToMin method

   // switchToMax(): transforms a min- to a max-priority queue; else leave unchanged.
   public void switchToMax()
   {
       if(currentState.equalsIgnoreCase(MIN_HEAP))
       {
           currentState = MAX_HEAP;
           rebuildHeap();
       }
   } // end of switchToMax method

   // stale (): returns the current state (Min or Max) of the priority queue.
   public String state()
   {
       return currentState;
   } // end of state method
  
   // isEmpty(): returns true if the priority queue is empty.
   public boolean isEmpty()
   {
       return numberOfEntries == 0;
   } // end of isEmpty method

   // size(): returns the current number of entries in the priority queue.
   public int size()
   {
       return numberOfEntries;
   } // end of size method
  
   // toString method implementation
   public String toString()
   {
       StringBuilder sb = new StringBuilder();
       sb.append("[");
       for(int i = 0; i < numberOfEntries; i++)
       {
           sb.append(heap[i]);  
          
           if(i < numberOfEntries - 1)
               sb.append(", ");
       }
       sb.append("]" );
      
       return sb.toString();
   } // end of toString method
      
   // rebuildHeap method implementation
   private void rebuildHeap()
   {
       for(int i = numberOfEntries / 2 - 1; i >= 0; i--)
       {
           heapify(i);
       }
   } // end of rebuildHeap method
  
   // heapify method implementation
   private void heapify(int index)
   {
       int current = index;
       int left = 2 * index + 1;
       int right = 2 * index + 2;

       if(currentState.equalsIgnoreCase(MIN_HEAP))
       {
           if(left < numberOfEntries && heap[index].getKey().compareTo(heap[left].getKey()) > 0)
           {
               current = left;
           }
          
           if(right < numberOfEntries && heap[current].getKey().compareTo(heap[right].getKey()) > 0)
           {
               current = right;
           }

       }      
      
       if(currentState.equalsIgnoreCase(MAX_HEAP))
       {
           if(left < numberOfEntries && heap[index].getKey().compareTo(heap[left].getKey()) < 0)
           {
               current = left;
           }
          
           if(right < numberOfEntries && heap[current].getKey().compareTo(heap[right].getKey()) < 0)
           {
               current = right;
           }
       }

       if(current != index)
       {          
           Entry<K, V> tempEntry = heap[index];
           heap[index] = heap[current];
           heap[current] = tempEntry;
          
           heapify(current);
       }
   } // end of heapify method  
} // end of FlexiblePriorityQueue class

File: FlexiblePriorityQueueTest.java

// FlexiblePriorityQueueTest class implementation
public class FlexiblePriorityQueueTest
{
   // start main method
   public static void main(String[] args)
   {
       FlexiblePriorityQueue<String, Integer> fpq = new FlexiblePriorityQueue<String, Integer>();
      
       fpq.insert("true", 1);
       fpq.insert("your", 2);
       fpq.insert("other", 3);
       fpq.insert("has", 4);
       fpq.insert("the", 5);
       fpq.insert("code", 6);
       fpq.insert("are", 7);
       fpq.insert("vice", 8);
       fpq.insert("versa", 9);
      
       System.out.println("Current State: " + fpq.state());      
       System.out.println("Entries: " + fpq);  
      
       System.out.println("\nRemoved top element: " + fpq.remove());
       System.out.println("Entries: " + fpq);
      
       System.out.println("\nToggling the state...");
       fpq.toggle();  
      
       System.out.println("\nCurrent State: " + fpq.state());      
       System.out.println("Entries: " + fpq);
      
       System.out.println("\nRemoved top element: " + fpq.remove());
       System.out.println("Entries: " + fpq);
   } // end of main method
} // end of FlexiblePriorityQueueTest class

Sample Output:

Current State: Min Heap Entries (are, 7),(other, 3), (code, 6),(versa, 9), (the, 5),(true, 1), (has, 4 (your, 2),(vice, 8)1 R

Add a comment
Know the answer?
Add Answer to:
In class, we discussed the priority queue (PQ) ADT implemented using min-heap. In a min-heap, the...
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
  • 5. Consider a priority queue of strings with an integer priority. The queue us implemented as...

    5. Consider a priority queue of strings with an integer priority. The queue us implemented as a min heap using a 0-based array of size 8 with methods push(entry, priority) and pop(). Determine the priority queue contents, represented both as an array and as a tree, at the points indicated below during the following operations on the ADT. Write down the queue contents after the operation on the given line is executed. 1. priority_queue<string, int> pq; 2. pq.push("start", 10); 3....

  • Write a program in Java to implement the max-priority queue using max-heap data structure. Implement the...

    Write a program in Java to implement the max-priority queue using max-heap data structure. Implement the max-heap data structure using an integer array of 10 cells. (Do not use Java in-built PriorityQueue class.) [In a max-heap, the root node and the intermediate node vales are always greater than their children.] First, take 10 integer values from the user and insert them in the max-priority queue. Then print the elements of the queue. After that, delete two elements from the queue...

  • I need help writing java code for the Binary Heap Priority Queue assignment. Task: // Deletes all...

    I need help writing java code for the Binary Heap Priority Queue assignment. Task: // Deletes all instances of the parameter obj from the PQ if found, and returns true. Returns false if no match to the parameter obj is found. public boolean delete(E obj); // provided ADT How can I write this in O(logn)? assuming you are using Sink/Swim (insert/remove) operations Additional info: Each method must be as efficient as possible. That is, an O(n) is unacceptable if the...

  • Min heap class implementation in Python. Implement a min-using an array. Your min-heap class will have...

    Min heap class implementation in Python. Implement a min-using an array. Your min-heap class will have one private attribute, an array of integers. Implement the following methods for the min-heap class You may not use the built-in min function. init - Constructor makes an empty heap str - Prints the heap out in any way you want for debugging only) makenull(self) - Makes the heap empty insert(self,x) - Insert element x into the heap parent(self,i) - Returns the index of...

  • A limited-sized Queue ADT is an abstract data type that has a limit on the length...

    A limited-sized Queue ADT is an abstract data type that has a limit on the length of the queue. It can be created with a static array of size N, where N is the maximum length of the array. In C, this structure can be defined as follows: typedef struct {int * data;//array of the data on the queue//you may add other attributes here but use as few as possible} queue_t; Write an (efficient) pseudocode for the implementation of each...

  • You are to simulate a dispatcher using a priority queue system. New processes are to be...

    You are to simulate a dispatcher using a priority queue system. New processes are to be entered using a GUI with priority included (numbering should be automatic). Processes are also to be terminated by GUI command. Context switches are to be by command with the cause of the switch being immaterial. Assume only one CPU. Priorities and numbers of processes can be kept small, just big enough to demonstrate the below listed functionality. You may pre-populate the queues initially from...

  • 1.Dijkstra's Algorithm [10 pt] In class, we have discussed an implementation of Dijkstra's Algorithm using min-heap....

    1.Dijkstra's Algorithm [10 pt] In class, we have discussed an implementation of Dijkstra's Algorithm using min-heap. Analyze the worst-case running time of an implementation of this algorithm using unordered linked-list (as the data structure for d(v), the upper bound on the shortest distance from source s to v). Give your answer in e. Justify your answer (and state any assumptions you make).

  • Using C++, data structures, C++ STL, inputs and expected outputs are shown below. Max Heap Heap...

    Using C++, data structures, C++ STL, inputs and expected outputs are shown below. Max Heap Heap is a specialized tree-based data structure that satisfies the heap property: if P is a parent node of C, then the key (the value) of P is either > (in a max heap) or s (in a min heap) the key of C. The node at the "top" of the heap (with no parents) is called the root node. In binary-tree based heap, it...

  • 2. Consider a circular array based Queue as we have discussed in the lectures (class definition...

    2. Consider a circular array based Queue as we have discussed in the lectures (class definition given below for reference) public class CircArrayQueue<E> implements Queue<E private EI Q private int front-0 indicates front of queue l indicates position after end of queue private int end-0: public CircArrayQueue( public int getSize (.. public boolean isEmpty ( public void enqueue (E e)... public E dequeue ) throws EmptyQueueException... Il constructor We are interested in implementing a Stack class based on the above...

  • Create a java code that will take user input and find the median using two heaps...

    Create a java code that will take user input and find the median using two heaps (max and min heap). The two heap must sort the elements from small to large. Running time must be efficient and below O(n^2). The algorithm must support the following methods: - insert(b): insert a given element b in O(logn) time - getMedian(): return the median in O(1) time - removeMedian(): remove and return the median in O(logn) time Note: The median will return the...

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