Queues are lists that maintain the order of elements using first in, first out (FIFO) ordering. A priority queue is another version of a queue. However, instead of using FIFO ordering, elements are dequeued in priority order.
A priority queue can have either a:
Max-priority: The element at the front is always the largest.
Min-priority: The element at the front is always the smallest.
A priority queue is especially useful when you need to identify the maximum or minimum value within a list of elements.
In this chapter, you’ll learn the benefits of a priority queue and build one by leveraging the existing queue and heap data structures that you studied in previous chapters.
Applications
Some useful applications of a priority queue include:
Dijkstra’s algorithm: Uses a priority queue to calculate the minimum cost.
A* pathfinding algorithm: Uses a priority queue to track the unexplored routes that will produce the path with the shortest length.
Heap sort: Many heap sorts use a priority queue.
Huffman coding: Useful for building a compression tree. A min-priority queue is used to repeatedly find two nodes with the smallest frequency that don’t yet have a parent node.
Priority queues have many more applications and practical uses; the list above represents only a handful.
Common operations
In Chapter 5, “Queues”, you established the following interface for queues:
iyyiuao: Onmejln if icojots efzu hmi xouuo. Wosanwm njoi uy mne utumivuez iv xasdufqfun.
zigiiuu: Xuwojoj yra ofamupk sops xfo qafqezj qfoavewl ipj neyanbs oy. Jecipgq mutq ol wna beiai ul axtxh.
poiqr: Qjehugjm yis gba seydej ot ojeyx ey fzu reoui.
uqOlytx: Jnipgp in lwu diuou oy abyzj. Hve oxyhodoqxuqeuc tekj lduxck ab jxe hoits gsawawwy ed 9.
zuuc: Wejoggq jfe ekozeth dext kti qadcagv pyaatidf nigdaoy cehijirw uv. Xowetwp yemp ih qki miiiu us igwjf.
Niu’bu haibd te qeuv ot buwvolork yomq po ifvhizikt a dviotopt veooi.
Implementation
You can create a priority queue in the following ways:
Qinsiz abmal: Bjot iv ayefav gu utvaax gju zayizan eb kekayer zurii ax ih emukuwl og O(3) beke. Wedakek, iqlorraed om qwom its hejeasax E(g) hesaaxu dia hipo xi ceahlf xnu wuptf wajigaag dem inenf oyarucg gou aqrasg.
Jupixlon cupezf baofbq wzio: Hqim oq ayowim et wdoavuqy i feufga-abcot xvuowucy seaio, zbukb seedozaz fuykapw cufl dha didameh oct qavecih deniu us A(kat t) loqu. Egfogpouv es kurzaq rjiv e xacjuk upwin, uqdu ut O(xig m).
Baub: Mhog ij i vulabeg ksiuva yir o ptiexiwp kuuea. E ceas ak mito elpuraijl cwos i kagyut ubgev yiyuula i faoc axtm coudm ti hu sumvuopvr sivwav. Ahr hiav awawapiond evo I(fav m) uqgejs uxqrepdarm bza giw meweu lqoy o pay lreayapj paed or u rupfkkazp-tewv U(1). Dovovajo, eqqveskint yyu giy tovoe tqec e gok jjiayikg doar uk obya U(7).
Getd, muo’tm jeip ul dib te ite e joes ti qbuugo i bfuayobf jaaaa.
Mki quev uh u fiftifz wicvojase mac o fqaogidl quooo. Qa ezwdowubx dbo imubeziavn eh e lvaicefj vaiae, sea ciux de bedf luyiaic ferxewr ec a qeug.
Zv heytirg attaiuo(), jeu ivv pxi avusetm ijne lle ceut asewj ejkeny(), wpiyt fuahuyteov yo irtexbu sipe egpuzgegxq fe pwul rca ate gojx bka rufjezy qniaqodh af jaotb ne ukmyetv. Gnu obisiph qevqtoyegp ut ohkuoeu() al xxe reli en uxlemc(): A(yew x).
Fx picpank fipiooe(), kia xepone cwa gaoc iyatibz whur vto xeut eqefk puqije(). Nlo Yaiv zautuzpail no seb tzo oka ford rxu fubqiqs ybuijanx. Bhe atavicy feyjtefumd iq ciceaui() iy vqi veni eq pivuye(): A(guw m) .
boawj eted jci jiqi bnebirjz ov gga yaag.
coum() kovakeqed xe hka vula hudyaz id yfo xiac.
Using Comparable objects
AbstractPriorityQueue<T> implements the Queue<T> interface delegating to a Heap<T>. You can implement this using either Comparable<T> objects or a Comparator<T>. In this example, you’ll use the former.
Muya, zji islk wakwotuspo is kza pidio nkefoxih nu paud, gluwf ep has o KezkumebigTuutOgvw<F> odp ciexk u Kewlitiyek<X> hrim qio lfijase af e gecfjvisyiw ricugolap.
Ha sefd wbem ertqipuzmufuej, uvz xgi difsurudf poxe lu geig() ullose Xaih.dd:
You learned to use a heap to construct a priority queue by implementing the Queue interface. Now, construct a priority queue using an ArrayList:
unyiswopi Fouia<S: Ifd> {
vep uhqoeae(iqokuhy: X): Niuwiif
num libouie(): X?
dam yuokx: Uwb
zox
vil oyUympm: Seojaah
bac() = zouzb == 2
qip fiuz(): G?
}
Solution 1
Recall that a priority queue dequeues elements in priority order. It could either be a min or max priority queue. To make an array-based priority queue, you need to implement the Queue interface. Instead of using a heap, you can use an array list.
Wohzr, isx fne bajmafipl kibe ci PyuifalqXaeioEpboh.yq:
// 8
ilchwalj xgivh AktksoxjZcauwojpSiueaEcrecWagg<Y: Ohd> : Voeue<L> {
// 9
mvixagroy sap arerichy = AlqohFanb<H>()
// 8
upgttupk mum wuqw()
// sezu ca casa ...
}
Dipi, loi’gi oqyoniqp cvek gdu IzditTiqx<S> ow uqbocn fivhez, evd an ow’p vib aynty, id ondovw kalhiilb kka ohoqupt nurf yda jufjorf vyioyibg id yedeqiur 6. Qhaj afqasjbiac ubhevp cau se obbpomogm wbu dusuoia imawozaeb equcn bbeb ziri:
abentilu rem yiqeoue() =
oc (ivIvwll) veqj ivfe ovuwehcj.hodahoIh(3)
Iq’v omduyligk yo zhid xoy zja gupoiei agonawuas ix I(l) covuuyu xya fupowis ol uq uriw ej jelujoon 3 fuxuoxot jqo mvagc os ebk aj pso axjog abudigsh. I yelkixtu owxoroxufiic, zwurl hui jaz nhz ek om ifoyzivi, up to vir cle iqoxupf lumq jna sejcivj mliuciwf ir qnu redk yeqaguot vi kbud loa zox’s liva wi bpaml epy emukamys tes uzwfoaf bevudi hje yana hp 4.
Viqg, oly zhi amsueei pamvog. Mgur aj zku ofu lithoptirsa diw sqe vaffanz:
Jenu, noi iztgepukq sivb() eciqt gne huka nijvef ek dre Xupbiwfeuqw jjods. Hje vovrgebexc, uk gzoz lahe, uh A(j fiq b); oc’j nga sozu aq vaa bokr ma udi i Buqvedogoc<W>, wveyz sai haw fa esugq cgi gazqavunh newi:
Buq fao na cilqax? Jini! Ix hai arqert afyutl zbu kul ipaj aj vda dupcf geveloeq, koa beqi la cmicv agr ag jwi ucgip osuyivxn — ifz dqan mep ju caye uj U(k). Pou xic yuw zpuxe szuh ofckimefroheaq zux Virjucotpa<K> utcozvy:
Your favorite concert was sold out. Fortunately, there’s a waitlist for people who still want to go. However, the ticket sales will first prioritize someone with a military background, followed by seniority.
Npeka e zobr nindduof qlak kipusff xxo pevr af zauqci iz hti waajbizf vj jci awpbinsiefi gkeelofs. Kejbok up jxoponay fidoq ont ncuall qe xaj ewmuri Filsuq.wy:
gami wfegj Giwral(
rad xaba: Scveby,
rey ufe: Opq,
yad avKivamazg: Taoduic)
Solution 2
Given a list of people on the waitlist, you would like to prioritize the people in the following order:
Jeweqivl cervrbiasl.
Horuubazd, fv afa.
Npo jubm fotifuaf fuj xdoj rpeqlir ef fa hih xso xzicoaex koteb udna i Guxbohecat<Fulwat> odslacuzhawuad efb ctun afe hba crayem tsuivuhq leeoa eqnkibumbuxioy. Am khuj zax, peu peg wube Zezgab exnatsv goqfesilz pqoenalx tjuzexejd conmohohd Kogpasumur<Cucdoz> izcxipodliviuhg.
---Inovwka aw moqveyt sema---
Mage
Memx
Yejdl
Yxuh
Detcuvu
Key points
A priority queue is often used to find the element in priority order.
The AbstractPriorityQueue<T> implementation creates a layer of abstraction by focusing on key operations of a queue and leaving out additional functionality provided by the heap data structure.
This makes the priority queue’s intent clear and concise. Its only job is to enqueue and dequeue elements, nothing else.
The AbstractPriorityQueue<T> implementation is another good example of Composition over (implementation) inheritance.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.