In: Computer Science
Remarks: In all algorithm, always explain how and why they work. If not by a proof, at least by a clear explanation. ALWAYS, analyze the running time complexity of your algorithms. In all algorithms, always try to get the fastest possible. A correct algorithm with slow running time may not get full credit. Do not write a program. Write pseudo codes or explain in words
Question 2: 1. Show how to implement a Queue by a Priority Queue. What is the run time per operation? 2. Show how to implement a Stack using Priority Queue. What is the run time per operation?
Solution 1- Priority Queue is a Queue where each element is assigned a priority and elements come out in order by priority. Typical use case of priority queue is scheduling jobs. Each job has a priority and we process jobs in order of decreasing priority. While the current job is processed and new jobs may arrive.
Priority Queue has some main operations:
Priority Queue is used in many algorithms:
Solution 2
Pseudocode
class Stack {
class Element { int prio, Key elem; };
MaxPriorityQueue<Element> q;
int top_priority = 0;
void push(Key x) { q.push(Element(top_priority++, x)); }
Key pop() { top_priority--; return q.pop().elem; }
};
LIFO behavior follows from the fact that every new element is pushed with a priority higher than all the current elements, so it will be popped before any of them.