UPI Study › Courses › Data Structures and Algorithms › Free lessons › Lesson 13.1 Free with a free account
The Priority Queue: Why Some Lines Need to Prioritize
Data Structures and Algorithms · Chapter 13: Priority Queues and HeapsSection 13.1 · lesson 52 of 8710 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Data Structures and Algorithms.
Lesson complete
Earn the 3 college credits for Data Structures and Algorithms
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Building a Priority Queue in Java, Step by Step →← Choosing the Right Tree: Layouts and ApplicationsNext lesson: Building a Priority Queue in Java, Step by Step →
In this lesson
Serving the most urgent element first instead of the earliest.
- Distinguish a priority queue from FIFO queues and stacks
- Use Java's PriorityQueue methods offer, poll, peek and remove correctly
- Build min and max priority queues with comparators and tie-breakers
- Recognize mistakes such as trusting printed order or changing priorities in place
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (1,322 words). Read along, or search it.
Opening Question
Who Matters Most Right Now
A hospital emergency room doesn't treat patients strictly in the order they arrive. A patient with a sprained ankle who came in first waits, while a patient with chest pain is seen at once. That waiting line isn't asking who has waited longest. It's asking who matters most, right now. Programs face the same situation: tasks compete for a processor, simulated events must happen in time order, and requests differ in urgency.
Limits of FIFO
A Plain Queue Ignores Urgency
A plain queue serves elements in the order they arrived. That's right for a bakery counter, where fairness means first come, first served. But a queue never looks at what an element is, so it can't tell an emergency from a routine visit. Picture eight patients, numbered by arrival, each with a severity from one, the most urgent, to five. Fay, with severity one, is the most urgent. She arrived sixth, so a first-in, first-out queue serves her sixth, after five less urgent patients. A program could search the queue before every removal, or keep a list sorted at all times. Both work, but each loads extra work onto one operation.
Abstract Data Type
Insert, Remove Min and Peek
A stack serves the element added last. A queue serves the element added first. A priority queue serves the element with the best priority, whenever it was added. Like a stack, it's defined by what its operations do, not by how it stores data. Insert adds an element with its priority. In Java, that's add or offer, and null is rejected. Remove min takes out the best element. Java's poll returns null on an empty queue, while remove throws. Peek returns the best without removing it: peek gives null when empty, and element throws. Is empty and size work as usual.
Worked Example
Mixing Insertions and Removals
Insertions and removals can be mixed freely. This program adds fifty and twenty, then polls. It gets twenty, the smaller of the two. Then it adds ten and sixty, and polls three more times: ten, fifty, sixty. Ten was added after fifty, but left before it. Each removal returns the best element inside at that moment, not the newest or the oldest.
Min Versus Max
Defining Which Element Is Best
Best has to be defined. In a min-priority queue, the smallest value is best. In a max-priority queue, the largest is. Severity one is most urgent, so triage needs min priority. A score or a bid, where bigger is better, needs max. A time stamp, where earlier comes first, needs min. Java's PriorityQueue is a min-priority queue by default. For max priority, pass a comparator that reverses the order. Both queues get forty, ten, thirty, twenty. Peek shows ten and forty, and peeking leaves the size at four. Emptying them returns sorted order: ascending for min, descending for max.
Quick Check
Poll, Add One, Poll Twice
Quick check. A default PriorityQueue gets eight, three and five. The program polls once, adds one, and then polls twice more. Which three values come out, in order? Pause and predict. It prints three, one, five. The first poll takes three, the smallest of eight, three and five. Then one arrives, and it's now the best inside, so the next poll returns it. Five comes after that. Three, five, eight ignores the one added later. And one, three, five would mean one was already inside at the first poll.
Worked Example
Ordering Patients With a Comparator
Real elements are rarely bare numbers. A patient has a name, a severity and an arrival number, and only some of these decide the order. Here, Patient is a Java record: a compact way to declare a type that only holds data. The comparator orders by severity first, and breaks ties with the arrival number. The eight patients go into a first-in, first-out queue and into the priority queue. The first line is arrival order. The second is triage order, and Fay moved from sixth to first. There's a price. Eli, with severity five, moved from fifth to eighth. A steady stream of urgent arrivals could keep a low-priority element waiting a very long time. That's why real systems often add a rule, such as raising the priority of elements that have waited long enough.
Tie-Breakers
Equal Severities Need a Tie-Breaker
Ana and Dee both have severity three. With the arrival tie-breaker, Ana, who came first, goes first. The third queue compares severity alone. In this run, Dee came out before Ana, and Gus before Cy. Without a tie-breaker, the order of equal elements isn't promised, and another Java version might differ. When equal priorities must be served fairly, add a tie-breaker.
Applications
Triage, Scheduling and Simulation
Three typical uses all rely on min priority. Hospital triage orders patients by severity. An operating system scheduler orders tasks by a priority number. And an event simulation orders future events by the time they happen.
Application
Scheduling Ready Tasks
A computer has more tasks ready than it can run at once. A scheduler keeps the ready tasks in a priority queue, and always runs the most important one next. In this sketch, a smaller number means a more important task. Some systems use the opposite convention, so always check the direction. The keyboard task runs first, then video, disk flush, and backup. Real schedulers are more elaborate, but the core question, which waiting task is next, is the one a priority queue answers.
Application
Event Simulation in Time Order
A simulation keeps a clock and a set of future events. Events are scheduled in any order, but must be handled in time order. A min-priority queue ordered by time does exactly that: remove the earliest event, set the clock to its time, handle it, and repeat. Handling an event can schedule new ones. When customer A arrives, the program schedules customer A leaves at time twenty-five. That event didn't exist when the run began. It was added while the queue was in use, and it still came out in the right place.
Quick Check
Serving the Highest Bid
Quick check. An auction program must always serve the highest bid first. It puts bids of seventy-two, ninety-five and eighty-eight into a new, default PriorityQueue. What does its first poll return? Pause, and decide. It returns seventy-two. A default PriorityQueue is a min-priority queue, so it hands out the smallest bid, silently. Ninety-five is what the auction wanted. It needs a max-priority queue, built with Comparator dot reverse order. And eighty-eight would come out of neither queue first: it's not the smallest or the largest.
Common Mistakes
Printed Order and Changed Priorities
A few mistakes are worth seeing run. First, adding fifty, forty, thirty, twenty, ten and printing the queue gives ten, twenty, forty, fifty, thirty. That's not sorted. Only poll is guaranteed to give the best element. Never read the printed form as an order. Second, an alert's priority changes from five to one after it's inserted. The queue doesn't notice, and peek still returns the email. The fix is to remove the element, change it, and add it again. Then the alert comes first. And an empty queue: poll and peek return null, while remove throws a no such element exception. Adding null throws a null pointer exception.
Looking Ahead
Two Simple Designs
So far, the priority queue has been a black box that keeps its promise: the best element comes out next. Two simple designs come to mind. An unsorted list, searched on every removal. Or a sorted list, kept in order on every insertion. Each is easy to write, and each makes one of the two main operations do much more work than the other.
Key Takeaways
Best Priority Comes Out Next
To sum up. A priority queue removes the element with the best priority next, whenever it was added. A FIFO queue looks only at arrival. Java's PriorityQueue is min-priority by default. Comparator dot reverse order gives max priority. A comparator picks the fields that decide the order. Add a tie-breaker when equal priorities must be fair. And the queue doesn't re-sort an element whose priority changes. Remove it, and add it again.
Think About It
A Low-Priority Patient Waits
Something to think about. A hospital orders patients by severity only. A severity-five patient arrives, and for hours a steady stream of severity one and two patients keeps coming. What happens to the first patient? Would a FIFO queue have the same problem, and what rule could protect low-priority patients?
About Data Structures and Algorithms at UPI Study
Data Structures and Algorithms (Computer Science 251) is a self-paced online course of 87 video lessons in 17 chapters, from Java and object-oriented design to arrays, linked lists, recursion, stacks and queues, trees, heaps, hash tables, sorting and graphs. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: Discrete Math vs Data Structures and Algorithms · Intro to Java vs Data Structures and Algorithms
Why take it here
Why students take Data Structures and Algorithms with UPI Study
Where the credit goes
Universities that work with NCCRS
Data Structures and Algorithms carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About The Priority Queue: Why Some Lines Need to Prioritize
What is a priority queue and how is it different from a regular queue?
How do you make a max priority queue in Java?
What is the difference between poll and remove in Java's PriorityQueue?
Why does a PriorityQueue not reorder an element after its priority changes?
About the Data Structures and Algorithms course
How many college credits is Data Structures and Algorithms?
How much does Data Structures and Algorithms cost and what is included?
Which universities accept UPI Study credits?
How long does Data Structures and Algorithms take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Data Structures and Algorithms.
87 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →