25
COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based on slides from D. Plaisted (UNC)

COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

  • Upload
    others

  • View
    28

  • Download
    0

Embed Size (px)

Citation preview

Page 1: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

COMP251:Heaps&Heapsort

JérômeWaldispühl SchoolofComputerScience

McGillUniversityFrom(Cormenetal.,2002)

BasedonslidesfromD.Plaisted(UNC)

Page 2: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

Heapdatastructure

•  Tree-baseddatastructure(here,binarytree,butwecanalsousek-arytrees)

•  Max-Heap–  Largestelementisstoredattheroot.–  forallnodesi,excludingtheroot,A[PARENT(i)]≥A[i].

•  Min-Heap–  Smallestelementisstoredattheroot.–  forallnodesi,excludingtheroot,excludingtheroot,A[PARENT(i)]≤A[i].

Page 3: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

Heaps–Example

26

24 20

18 17 19 13

12 14 11

Max-heapasabinarytree.

Lastrowfilledfromleftoright.

Page 4: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

Heapsasarrays

26 24 20 18 17 19 13 12 14 11

12345678910

Max-heapasanarray.

26

24 20

18 17 19 13

12 14 11

Mapfromarrayelementstotreenodesandviceversa•  Root–A[1]•  Lef[i]–A[2i]•  Right[i]–A[2i+1]•  Parent[i]–A[⎣i/2⎦]

1

2 3

4 5 6 7

8 9 10

Page 5: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

Height

•  Heightofanodeinatree:thenumberofedgesonthelongestsimplepathdownfromthenodetoaleaf.

•  Heightofaheap=heightoftheroot=Θ(lgn).•  MostBasicoperaionsonaheapruninO(lgn)ime

•  Shapeofaheap

Page 6: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

SoringwithHeaps•  Usemax-heapsforsoring.•  Thearrayrepresentaionofmax-heapisnotsorted.•  Stepsinsoring–  Convertthegivenarrayofsizentoamax-heap(BuildMaxHeap)–  Swapthefirstandlastelementsofthearray.

•  Now,thelargestelementisinthelastposiion–whereitbelongs.•  Thatleavesn–1elementstobeplacedintheirappropriatelocaions.

•  However,thearrayoffirstn–1elementsisnolongeramax-heap.•  Floattheelementattherootdownoneofitssubtreessothatthearrayremainsamax-heap(MaxHeapify)

•  Repeatstep2unilthearrayissorted.

Page 7: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

Heapsort•  Combinesthebekerakributesofmergesortandinserionsort.– Likemergesort,butunlikeinserionsort,runningimeisO(nlgn).

– Likeinserionsort,butunlikemergesort,sortsinplace.

•  Introducesanalgorithmdesigntechnique– Createdatastructure(heap)tomanageinformaionduringtheexecuionofanalgorithm.

•  Theheaphasotherapplicaionsbesidesoring.– PriorityQueues(SeeCOMP250)

Page 8: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

Maintainingtheheapproperty•  Supposetwosubtreesaremax-heaps,buttherootviolatesthemax-heapproperty.

•  Fixtheoffendingnodebyexchangingthevalueatthenodewiththelargerofthevaluesatitschildren.–  Theresulingtreemayhaveasubtreethatisnotaheap.

•  Recursivelyfixthechildrenunilallofthemsaisfythemax-heapproperty.

Page 9: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

MaxHeapify–Example26

14 20

24 17 19 13

12 18 11

14

14

2424

14

14

1818

14MaxHeapify(A,2)

Noden=2

Page 10: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

ProcedureMaxHeapify

MaxHeapify(A, i, n)1. l ← leftNode(i)2. r ← rightNode(i)3. if l ≤ heap-size[A] and A[l]>A[i]4. then largest ← l5. else largest ← i6. if r ≤ n and A[r]>A[largest]7. then largest ← r8. if largest ≠ i9. then exchange A[i] ↔ A[largest]10. MaxHeapify(A, largest)

Assump&on:Lef(i)andRight(i)aremax-heaps. nisthesizeoftheheap.

Timetofixnodeianditschildren=Θ(1)

Timetofixthesubtreerootedatoneofi’schildren=T(sizeofsubtree)

Page 11: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

WorstcaserunningimeofMaxHeapify(A,n)

•  T(n)=T(largest)+Θ(1)

•  largest≤2n/3(worstcaseoccurswhenthelastrowoftreeisexactlyhalffull)

•  T(n)≤T(2n/3)+Θ(1)⇒T(n)=O(lgn)

•  Alternately,MaxHeapifytakesO(h)wherehistheheightofthenodewhereMaxHeapifyisapplied

Page 12: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

≤2 ⋅n3

≤n3

Ο(log(n))

WorstcaserunningimeofMaxHeapify(A,n)

Page 13: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

Buildingaheap

•  UseMaxHeapifytoconvertanarrayAintoamax-heap.•  CallMaxHeapifyoneachelementinabokom-upmanner.

BuildMaxHeap(A)1. n ← length[A]2. for i ← ⎣length[A]/2⎦ downto 13. do MaxHeapify(A, i, n)

Page 14: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

BuildMaxHeap–Example

24 21 23 22 36 29 30 34 28 27

InputArray:

24

21 23

22 36 29 30

34 28 27

Staringtree(notmax-heap)

Page 15: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

BuildMaxHeap–Example

24

21 23

22 36 29 30

34 28 27MaxHeapify(⎣10/2⎦=5)

3636

MaxHeapify(4)

2234

22

MaxHeapify(3)

2330

23

MaxHeapify(2)

2136

21

MaxHeapify(1)

2436

2434

2428

24

21

21

27

Page 16: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

CorrectnessofBuildMaxHeap•  LoopInvariant:Atthestartofeachiteraionoftheforloop,

eachnodei+1,i+2,…,nistherootofamax-heap.•  Ini&aliza&on:–  Beforefirstiteraioni=⎣n/2⎦–  Nodes⎣n/2⎦+1,⎣n/2⎦+2,…,nareleaves,hencerootsoftrivialmax-heaps.

•  Maintenance:–  ByLI,subtreesatchildrenofnodeiaremaxheaps.–  Hence,MaxHeapify(i)rendersnodeiamaxheaproot(whilepreservingthemaxheaprootpropertyofhigher-numberednodes).

–  Decremeningireestablishestheloopinvariantforthenextiteraion.

Page 17: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

RunningTimeofBuildMaxHeap•  Looseupperbound:–  CostofaMaxHeapifycall×No.ofcallstoMaxHeapify–  O(lgn)×O(n)=O(nlgn)

•  Tighterbound:–  CostofMaxHeapifyisO(h).–  ≤⎡n/2h+1⎤nodesofheighth.–  Heightofheapis

n2h+1

!

""#

$$h=0

lgn"% $&

∑ O(h) =O n h2h

h=0

lgn"% $&

∑(

)**

+

,--=O(n)

lgn!" #$

RunningimeofBuildMaxHeapisO(n)

Page 18: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

Heapsort

1.  Buildsamax-heapfromthearray.

2.  Putthemaximumelement(i.e.theroot)atthecorrectplaceinthearraybyswappingitwiththeelementinthelastposiioninthearray.

3.  “Discard”thislastnode(knowingthatitisinitscorrectplace)bydecreasingtheheapsize,andcallMAX-HEAPIFYonthenewroot.

4.  Repeatthisprocess(goto2)unilonlyonenoderemains.

Page 19: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

Heapsort(A)

HeapSort(A)1. Build-Max-Heap(A)2. for i ← length[A] downto 23. do exchange A[1] ↔ A[i] 4. MaxHeapify(A, 1, i-1)

Page 20: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

Heapsort–Example

7

4 3

1 2

7 4 3 1 2

Page 21: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

Heapsort–Example

2

4 3

1

2 4 3 1 7

7

4

2 3

1

4 2 3 1 7

Heapify

Page 22: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

Heapsort–Example

1

2 3

1 2 3 4 7

7

3

2 1

3 2 1 4 7

Heapify

4

Page 23: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

Heapsort–Example

1

2

1 2 3 4 7

7

2

1

2 1 3 4 7

Heapify

4 3

Page 24: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

Heapsort–Example

1

2

1 2 3 4 7

7

1 2 3 4 7

4 3

Page 25: COMP251: Heaps & Heapsortjeromew/COMP251material/COMP...COMP251: Heaps & Heapsort Jérôme Waldispühl School of Computer Science McGill University From (Cormen et al., 2002) Based

HeapProceduresforSoring

•  BuildMaxHeapO(n)•  forloopn-1imes(i.e.O(n))– exchangeelementsO(1)– MaxHeapifyO(lgn)

=>HeapSortO(nlgn)