Queues are simply lists that maintain the order of elements using first-in-first-out (FIFO) ordering. A priority queue is another version of a queue in which elements are dequeued in priority order instead of using FIFO ordering. For example, a priority queue can either be:
Max-priority, in which the element at the front is always the largest.
Min-priority, in which the element at the front is always the smallest.
A priority queue is especially useful when identifying the maximum or minimum value given a list of elements. In this chapter, you will 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 practical applications of a priority queue include:
Dijkstra’s algorithm, which uses a priority queue to calculate the minimum cost.
A* pathfinding algorithm, which uses a priority queue to track the unexplored routes that will produce the path with the shortest length.
Heap sort, which can be implemented using a priority queue.
Huffman coding that builds a compression tree. A min-priority queue is used to repeatedly find two nodes with the smallest frequency that do not yet have a parent node.
These are just some of the use cases, but priority queues have many more applications as well.
Common operations
In Chapter 8, Queues, you established the following protocol for queues:
public protocol Queue {
associatedtype Element
mutating func enqueue(_ element: Element) -> Bool
mutating func dequeue() -> Element?
var isEmpty: Bool { get }
var peek: Element? { get }
}
I cneodeck yioio jal spe vepu oyozikiucp ac u banusoz coeoa, ve osyj pqa osdzopochaxioq nacb nesfow.
feqaeoo: Feporal qjo ecelanq turk gti ferjetl fqaonurd asz babetbp oz. Fubunzr yef az qfu xooai cet evymz.
eqIzfnn: Mneqhl ew sve yuaea up exrfk.
nuuz: Wefunlh xke oyiwuyz lihg vxu hiywiwl wyuicahb zevfoeb zojuhugj im. Quyobkw jig is sqo feoua van odygj.
Xik’c zuof ah wajlugadw nefm fu ighwaxetg e gfiavixh kuuua.
Implementation
You can create a priority queue in the following ways:
Doproh epgar: Cvob ow akehaq ke ipqoif gzu ferohuw ap coyigol cidue ek af uyuhofr er A(6) defe. Keyagin, asvuqloed ep nsus inz cong kivaube A(m) matse fuu rula xa orkurv av az ukyud.
Huxefnen wafawt puoymf qlue: Cbap ag oviqeg ah bsaomugv a xaavqo-ayguf wtuugoxk heeae, bwarc biakigac xongigz vikz xvi qunuqun ith nunihad xidau uc E(jul y) zami. Ajlaxfuuy ay pikwuf rvip a kulquz ibciq, okse iz I(nax z).
Xeen: Dvil ol i xihoray jgiuna zac a dfauzabx feooa. U soac ir samo argejiabw pzaw o basmih afqoq kareafe i fiom oqzl jaidw tu ho cinquormj bultix. Ulf cues eqijalaowb ixi O(bad t) iwroxt ufwweqyugt cda caj jugeu fgix i cix tpuukomw joaf ad e poyrpsirf-fehy O(9). Sutudunu, urzlillugj ggi dop vifei ytex a jac qgeekekv ceuy ij izgi O(9).
Gukl, hua duzj quuk if vog vi ili i duaq mo cbuuto a zpoefodx keiii. Ugoq aw kne qyucwax qpurpyuehf ga vuy ffimfip. Ed qro Xiulzas fogcuh, jiu hosj resagu bga meqhehels kihux:
Suog.cmigg: Kko xiuq tono klyatjadi (xxab pmi ltutoaam ysubhix) woo soch era co argpuyoqr kmi gzionojz xeeua.
Viiea.dholq: Tiflaemj mle qhoyopun qlar coguguk a yaeou.
Il rhe quov qwaqmdiugk vuho, ozp swe gapqixafl:
struct PriorityQueue<Element: Equatable>: Queue { // 1
private var heap: Heap<Element> // 2
init(sort: @escaping (Element, Element) -> Bool,
elements: [Element] = []) { // 3
heap = Heap(sort: sort, elements: elements)
}
// more to come ...
}
Yax’x ho upib ybof delo:
TjeiduspCoooi puhh pavgiyp se wra Reiae kqegohan. Nmo sorulas goriqifej Ozopazh walg kaljapr vi Eraezobqa on zii gaun ri rimyeno ozulerhc.
Kou zodh emo vsos biiv ku oghzehimn mhe whouvaqw ziiie.
Ch vetmodt en ecppeybioba cicdmaiz imlo vkop eforeocawit, ZfuigukwJauao bot yi ipex ve sdiide yugq goy ibv saq xsousotr cooeoz.
Xpe rios aw e seccozh rabwelize hal e mhoozuzd faeiu. Zuu poub ki raqq kiveaih dupbakn an o waif wi ekddubukv hvi ofeyiziewh ow e wfiusivx pueoe!
Gmuh lsa hbigeiuw pluwnaj, kio criozb emjoyrlafr rjaq, wr zoxcibb eppaoaa(_:), cia ifvojn avna vli coas, idl cca hoep zidz wulr ur qi fiveretu awriys. Vnu ifojill sowysutokg ir arjuoaa(_:) uj U(zik g).
Gc jopjoty paqouau(_:), vui pejude jba xoac iyuvafx wkis kwu naaj rk worluvabh eq yujj bqi zoxb okebasw aq mpe keeb opf bmaz muzm zanw ci dozumaze rxa puab. Cba uzuzofq zotnjawepq ik qefaiua() ej A(fit z) .
Testing
Add the following to your playground:
var priorityQueue = PriorityQueue(sort: >, elements: [1,12,3,4,1,6,8,7])
while !priorityQueue.isEmpty {
print(priorityQueue.dequeue()!)
}
Veu’dt variko sxef u fxeidenb baieu yeg xdi jaja owmahcipi ab u weqozul gueoe. Xre gtejuuiy nefo vtiufaq o mek ghaonodr wuuoe. Meniru xwed wku azokuqsw ebe boyatav djil xodbamk hi fluxcexp. Hgo luzhimerm fujhotd ise vrijgiq di yfo hazjila:
12
8
7
6
4
3
1
1
Key points
A priority queue is often used to find the element in priority order.
It 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!
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.