Heap orderingLeftcomplete Binary Tree143169101 Figure11HeapNexttimewewillshowhowthepriorityqueueoperationsareimplementedforaheapLecture13HeapSortTuesdayMar101998Chapt7inCLRRecallthataheapisa ID: 478226
Download Pdf The PPT/PDF document "LectureNotesCMSC251Aheapisrepresentedasa..." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
LectureNotesCMSC251Aheapisrepresentedasanbinarytree.Thismeansthatallthelevelsofthetreearefullexceptthebottommostlevel,whichislledfromlefttoright.Anexampleisshownbelow.Thekeysofaheaparestoredinsomethingcalledheaporder.Thismeansthatforeachnode,otherthantheroot,Parent.Thisimpliesthatasyoufollowanypathfromaleaftotherootthekeys Heap orderingLeft-complete Binary Tree143169101 Figure11:Heap.Nexttimewewillshowhowthepriorityqueueoperationsareimplementedforaheap.Lecture13:HeapSort(Tuesday,Mar10,1998)Chapt7inCLR.Recallthataheapisadatastructurethatsupportsthemainpriorityqueueoperations(insertandextractmax)in LectureNotesCMSC251 1 5 6 7 8 9 161410 8 7 9 4 2 1 Figure12:Storingaheapinanarray.Weclaimthattoaccesselementsoftheheapinvolvessimplearithmeticoperationsonthearrayindices.Inparticularitiseasytoseethefollowing.LeftRightParentIsLeafLeft.(Thatis,if'sleftchildisnotinthetree.)IsRoot==1Forexample,theheaporderingpropertycanbestatedasforall,if(notIsRoot)thenthenParententi].Soisaheapabinarytreeoranarray?Theansweristhatfromaconceptualstandpoint,itisabinarytree.However,itisimplemented(typically)asanarrayforspaceefciency.MaintainingtheHeapProperty:Thereisoneprincipaloperationformaintainingtheheapproperty.Itis.(Inotherbooksitissometimescalledsiftingdown.)Theideaisthatwearegivenanelementoftheheapwhichwesuspectmaynotbeinvalidheaporder,butweassumethatallofothertheelementsinthesubtreerootedatthiselementareinheaporder.Inparticularthisrootelementmaybetoosmall.Toxthiswesiftitdownthetreebyswappingitwithoneofitschildren.Whichchild?Weshouldtakethelargerofthetwochildrentosatisfytheheaporderingproperty.Thiscontinuesrecursivelyuntiltheelementiseitherlargerthanbothitschildrenoruntilitsfallsallthewaytotheleaflevel.Hereisthepseudocode.Itisgiventheheapinthearray,andtheindexofthesuspectedelement,andthecurrentactivesizeoftheheap.Theelementelementmax]issettothemaximumofofi]andittwochildren.Ifthenweswapapi]andA[max]andthenrecurseon Heapify(arrayA,inti,intm){//siftdownA[i]inA[1..m]l=Left(i)//leftchildr=Right(i)//rightchildmax=iif(lmandA[l]=-60;A[max])max=l//leftchildexistsandlargerif(rmandA[r]=-60;A[max])max=r//rightchildexistsandlargerif(max!=i){//ifeitherchildlargerswapA[i]withA[max]//swapwithlargerchildHeapify(A,max,m)//andrecurse LectureNotesCMSC251 SeeFigure7.2onpage143ofCLRforanexampleofhowHeapifyworks(inthecasewhere=10Weshowtheexecutiononatree,ratherthanonthearrayrepresentation,sincethisisthemostnaturalwaytoconceptualizetheheap.Youmighttrysimulatingthissamealgorithmonthearray,toseehowitworksatanerdetails.NotethattherecursiveimplementationofHeapifyisnotthemostefcient.Wehavedonesobecausemanyalgorithmsontreesaremostnaturallyimplementedusingrecursion,soitisnicetopracticethishere.Itispossibletowritetheprocedureiteratively.Thisisleftasanexercise.TheHeapSortalgorithmwillconsistoftwomajorparts.Firstbuildingaheap,andthenextractingthemaximumelementsfromtheheap,onebyone.WewillseehowtouseHeapifytohelpusdobothofHowlongdoesHepifytaketorun?ObservethatweperformaconstantamountofworkateachlevelofthetreeuntilwemakeacalltoHeapifyatthenextlowerlevelofthetree.Thuswedoworkforeachlevelofthetreewhichwevisit.Sincetherearelevelsaltogetherinthetree,thetotaltimeforHeapifyis.(Itisnotsince,forexample,ifwecallHeapifyonaleaf,thenitwillterminateinBuildingaHeap:WecanuseHeapifytobuildaheapasfollows.Firstwestartwithaheapinwhichtheelementsarenotinheaporder.Theyarejustinthesameorderthattheyweregiventousinthearray.WebuildtheheapbystartingattheleaflevelandtheninvokeHeapifyoneachnode.(Note:Wecannotstartatthetopofthetree.Whynot?BecausethepreconditionwhichHeapifyassumesisthattheentiretreerootedatnodeisalreadyinheaporder,exceptfor.)Actually,wecanbeabitmoreefcient.Sinceweknowthateachleafisalreadyinheaporder,wemayaswellskiptheleavesandstartwiththerstnonleafnode.Thiswillbeinposition.(Canyouseewhy?)Hereisthecode.Sincewewillworkwiththeentirearray,theparameterforHeapify,whichindicatesthecurrentheapsizewillbeequalto,thesizeofarray,inallthecalls. BuildHeap(intn,arrayA[1..n]){//buildheapfromA[1..n]fori=n/2downto1{Heapify(A,i,n) AnexampleofBuildHeapisshowninFigure7.3onpage146ofCLR.SinceeachcalltoHeapifytakestime,andwemakeroughlycallstoit,thetotalrunningtimeis2)log.Nexttimewewillshowthatthisactuallyrunsfaster,andinfactitrunsinWecannowgivetheHeapSortalgorithm.Theideaisthatweneedtorepeatedlyextractthemaximumitemfromtheheap.Aswementionedearlier,thiselementisattherootoftheheap.Butonceweremoveitweareleftwithaholeinthetree.Toxthiswewillreplaceitwiththelastleafinthetree(theoneatpositionpositionm]).Butnowtheheaporderwillverylikelybedestroyed.SowewilljustapplyHeapifytotheroottoxeverythingbackup. HeapSort(intn,arrayA[1..n]){//sortA[1..n]BuildHeap(n,A)//buildtheheapm=n//initiallyheapcontainsallwhile(m=2){swapA[1]withA[m]//extractthem-thlargestm=m-1//unlinkA[m]fromheap LectureNotesCMSC251Heapify(A,1,m)//fixthingsup AnexampleofHeapSortisshowninFigure7.4onpage148ofCLR.WemakecallstoHeapify,eachofwhichtakestime.Sothetotalrunningtimeis1)logLecture14:HeapSortAnalysisandPartitioning(Thursday,Mar12,1998)Chapt7and8inCLR.Thealgorithmwepresentforpartitioningisdifferentfromthetexts.HeapSortAnalysis:LasttimewepresentedHeapSort.Recallthatthealgorithmoperatedbyrstbuildingaheapinabottom-upmanner,andthenrepeatedlyextractingthemaximumelementfromtheheapandmovingittotheendofthearray.Onecleveraspectofthedatastructureisthatitresidesinsidethearraytobesorted.WearguedthatthebasicheapoperationofHeapifyrunsintime,becausetheheaphaslevels,andtheelementbeingsiftedmovesdownonelevelofthetreeafteraconstantamountofwork.Basedonthiswecanseethat(1)thatittakestimetobuildaheap,becauseweneedtoapplyHeapifyroughlytimes(toeachoftheinternalnodes),and(2)thatittakestimetoextracteachofthemaximumelements,sinceweneedtoextractroughlyelementsandeachextractioninvolvesaconstantamountofworkandoneHeapify.ThereforethetotalrunningtimeofHeapSortisIsthistight?Thatis,istherunningtime?Theanswerisyes.Infact,laterwewillseethatitisnotpossibletosortfasterthantime,assumingthatyouusecomparisons,whichHeapSortdoes.However,itturnsoutthattherstpartoftheanalysisisnottight.Inparticular,theBuildHeapprocedurethatwepresentedactuallyrunsintime.AlthoughinthewidercontextoftheHeapSortalgorithmthisisnotsignicant(becausetherunningtimeisdominatedbytheextractionNonethelesstherearesituationswhereyoumightnotneedtosortalloftheelements.Forexample,itiscommontoextractsomeunknownnumberofthesmallestelementsuntilsomecriterion(dependingontheparticularapplication)ismet.Forthisreasonitisnicetobeabletobuildtheheapquicklysinceyoumaynotneedtoextractalltheelements.BuildHeapAnalysis:LetusconsidertherunningtimeofBuildHeapmorecarefully.Asusual,itwillmakeourlivessimplebymakingsomeassumptionsabout.Inthiscasethemostconvenientassumptionisisoftheform,whereistheheightofthetree.Thereasonisthataleft-completetreewiththisnumberofnodesisacompletetree,thatis,itsbottommostlevelisfull.Thisassumptionwillsaveusfromworryingaboutoorsandceilings.Withthisassumption,level0ofthetreehas1node,level1has2nodes,anduptolevel,whichhasnodes.AlltheleavesresideonlevelRecallthatwhenHeapifyiscalled,therunningtimedependsonhowfaranelementmightsiftdownbeforetheprocessterminates.Intheworstcasetheelementmightsiftdownallthewaytotheleaflevel.Letuscounttheworkdonelevelbylevel.Atthebottommostleveltherearenodes,butwedonotcallHeapifyonanyofthesesotheworkis0.Atthenexttobottommostleveltherearenodes,andeachmightsiftdown1level.Atthe3rdlevelfromthebottomtherearenodes,andeachmightsiftdown2levels.Ingeneral,atlevel