PriorityQueue - - PDF document

priority queue
SMART_READER_LITE
LIVE PREVIEW

PriorityQueue - - PDF document

PriorityQueue


slide-1
SLIDE 1

1

1

  • 2
  • !
  • "#

$ % &%

PriorityQueue

3 4

  • Hidden

Implementation

SortedSequence UnsortedSequence

5

  • %$

'# % ' ()!$≤ ≤ ≤ ≤

:k≤ ≤ ≤ ≤ k :ifk1≤ ≤ ≤ ≤ k2andk2≤ ≤ ≤ ≤ k1,thenk1 k2 :ifk1≤ ≤ ≤ ≤ k2andk2≤ ≤ ≤ ≤ k3,thenk1≤ ≤ ≤ ≤ k3

6

Totalorderingexamples

  • ≤ isatotalordering
  • ≥ isalsoatotalordering
  • Alphabeticalorder:wedefinea≤ bif‘a’ is

before‘b’ inalphabeticalorder

  • Reversealphabeticalorder
slide-2
SLIDE 2

2

7

But…

  • arenottotalorderingssince

theyarenotreflexive

  • isnotatotalorderingsincewecan’t

compareany2elementswith=. Givena,b,wedonotalwayshave

  • 8

Moreexamplesofordering

Wecanordertheco/ordinatepairs p=(x1,y1)andq=(x2,y2)by

  • p≤ q ifx1≤ x2
  • p≤ qif

y1 ≤ y2

  • p≤ qifx1≤ x2and y1 ≤ y2

Thelastoneisonlyapartial ordering!

9

!

# *+,-# )$ *,-#

  • *,%!-#%%

*,-# ),$&- %.

  • *',-#

)%. */,-#) %.

10

"#

$ % # $0 1$0"%$ $0 $ $0 # *2,!$- *2(,!$- *,!$- *3,!$- *3(,!$- *1$,-

11

$#%& '(

4 !%! %!! ,- 52,- )*+,

12

$#%&'( ),+

  • 6,-!',-!/,-!

% 4

  • )+,
slide-3
SLIDE 3

3

13

$#%''(

744!$% ,-!',-! /,- %)*+

  • However,toimplementinsertItem(), wemustnowscanthroughthe

entiresequenceintheworstcase.ThusinsertItem() runsin

14

Anobservation… Withanunsortedsequence… removeMin()always takesO(n) Butwithasortedsequence… insertItem()takesatmost O(n)

15

##-'.

$ 4$# 8 . 4 ,!- 8 . $%4 /,-

16

AlgorithmPriorityQueueSort(S,P): Input:AsequenceSstoringnelements,onwhicha totalorderrelationisdefined,andaPriority QueuePthatcompareskeyswiththesamerelation Output:TheSequenceSsortedbythetotal

  • rderrelation

while!S.isEmpty() do e← S.removeFirst() P.insertItem(e,e) whilePisnotemptydo e← P.removeMin() S.insertLast(e)

17

## - ''

VariationofPriorityQueueSort thatusesanunsortedsequence to implementthepriorityqueueP. – Phase1,theinsertionofanitemintoPtakesO(1)time – Phase2,removinganitemfromPtakestimeproportionaltothe currentnumberofelementsinP

  • 18

''),+

) 4*#

  • %,-

) / %

  • 9:;:<:

4*,2-

slide-4
SLIDE 4

4

19

## - $'

4 (

  • 20

$'),+

) *#

  • %

9:;:<: ) / %,- *,2-