Heapsort - Wikipedia
文章推薦指數: 80 %
Heapsort can be thought of as an improved selection sort: like selection sort, heapsort divides its input into a sorted and an unsorted region, and it ... Heapsort FromWikipedia,thefreeencyclopedia Jumptonavigation Jumptosearch Asortingalgorithmwhichusestheheapdatastructure HeapsortArunofheapsortsortinganarrayofrandomlypermutedvalues.Inthefirststageofthealgorithmthearrayelementsarereorderedtosatisfytheheapproperty.Beforetheactualsortingtakesplace,theheaptreestructureisshownbrieflyforillustration.ClassSortingalgorithmDatastructureArrayWorst-caseperformance O ( n log n ) {\displaystyleO(n\logn)} Best-caseperformance O ( n log n ) {\displaystyleO(n\logn)} (distinctkeys)or O ( n ) {\displaystyleO(n)} (equalkeys)Averageperformance O ( n log n ) {\displaystyleO(n\logn)} Worst-casespacecomplexity O ( n ) {\displaystyleO(n)} total O ( 1 ) {\displaystyleO(1)} auxiliary Incomputerscience,heapsortisacomparison-basedsortingalgorithm.Heapsortcanbethoughtofasanimprovedselectionsort:likeselectionsort,heapsortdividesitsinputintoasortedandanunsortedregion,andititerativelyshrinkstheunsortedregionbyextractingthelargestelementfromitandinsertingitintothesortedregion.Unlikeselectionsort,heapsortdoesnotwastetimewithalinear-timescanoftheunsortedregion;rather,heapsortmaintainstheunsortedregioninaheapdatastructuretomorequicklyfindthelargestelementineachstep.[1] Althoughsomewhatslowerinpracticeonmostmachinesthanawell-implementedquicksort,ithastheadvantageofamorefavorableworst-caseO(nlogn)runtime.Heapsortisanin-placealgorithm,butitisnotastablesort. HeapsortwasinventedbyJ.W.J.Williamsin1964.[2]Thiswasalsothebirthoftheheap,presentedalreadybyWilliamsasausefuldatastructureinitsownright.[3]Inthesameyear,RobertW.Floydpublishedanimprovedversionthatcouldsortanarrayin-place,continuinghisearlierresearchintothetreesortalgorithm.[3] Contents 1Overview 2Algorithm 2.1Pseudocode 3Variations 3.1Floyd'sheapconstruction 3.2Bottom-upheapsort 3.3Othervariations 4Comparisonwithothersorts 5Example 5.1Buildtheheap 5.2Sorting 6Notes 7References 8Externallinks Overview[edit] Theheapsortalgorithmcanbedividedintotwoparts. Inthefirststep,aheapisbuiltoutofthedata(seeBinaryheap§ Buildingaheap).Theheapisoftenplacedinanarraywiththelayoutofacompletebinarytree.Thecompletebinarytreemapsthebinarytreestructureintothearrayindices;eacharrayindexrepresentsanode;theindexofthenode'sparent,leftchildbranch,orrightchildbrancharesimpleexpressions.Forazero-basedarray,therootnodeisstoredatindex0;ifiistheindexofthecurrentnode,then iParent(i)=floor((i-1)/2)wherefloorfunctionsmaparealnumbertothelargestleadinginteger. iLeftChild(i)=2*i+1 iRightChild(i)=2*i+2 Inthesecondstep,asortedarrayiscreatedbyrepeatedlyremovingthelargestelementfromtheheap(therootoftheheap),andinsertingitintothearray.Theheapisupdatedaftereachremovaltomaintaintheheapproperty.Onceallobjectshavebeenremovedfromtheheap,theresultisasortedarray. Heapsortcanbeperformedinplace.Thearraycanbesplitintotwoparts,thesortedarrayandtheheap.Thestorageofheapsasarraysisdiagrammedhere.Theheap'sinvariantispreservedaftereachextraction,sotheonlycostisthatofextraction. Algorithm[edit] Theheapsortalgorithminvolvespreparingthelistbyfirstturningitintoamaxheap.Thealgorithmthenrepeatedlyswapsthefirstvalueofthelistwiththelastvalue,decreasingtherangeofvaluesconsideredintheheapoperationbyone,andsiftingthenewfirstvalueintoitspositionintheheap.Thisrepeatsuntiltherangeofconsideredvaluesisonevalueinlength. Thestepsare: CallthebuildMaxHeap()functiononthelist.Alsoreferredtoasheapify(),thisbuildsaheapfromalistin O ( n ) {\displaystyleO(n)} operations. Swapthefirstelementofthelistwiththefinalelement.Decreasetheconsideredrangeofthelistbyone. CallthesiftDown()functiononthelisttosiftthenewfirstelementtoitsappropriateindexintheheap. Gotostep(2)unlesstheconsideredrangeofthelistisoneelement. ThebuildMaxHeap()operationisrunonce,andisO(n)inperformance.ThesiftDown()functionisO(logn),andiscalledntimes.Therefore,theperformanceofthisalgorithmisO(n+nlogn)=O(nlogn). Pseudocode[edit] Thefollowingisasimplewaytoimplementthealgorithminpseudocode.Arraysarezero-basedandswapisusedtoexchangetwoelementsofthearray.Movement'down'meansfromtheroottowardstheleaves,orfromlowerindicestohigher.Notethatduringthesort,thelargestelementisattherootoftheheapata[0],whileattheendofthesort,thelargestelementisina[end]. procedureheapsort(a,count)is input:anunorderedarrayaoflengthcount (Buildtheheapinarrayasothatlargestvalueisattheroot) heapify(a,count) (Thefollowingloopmaintainstheinvariantsthata[0:end]isaheapandeveryelement beyondendisgreaterthaneverythingbeforeit(soa[end:count]isinsortedorder)) end←count-1 whileend>0do (a[0]istherootandlargestvalue.Theswapmovesitinfrontofthesortedelements.) swap(a[end],a[0]) (theheapsizeisreducedbyone) end←end-1 (theswapruinedtheheapproperty,sorestoreit) siftDown(a,0,end) Thesortingroutineusestwosubroutines,heapifyandsiftDown.Theformeristhecommonin-placeheapconstructionroutine,whilethelatterisacommonsubroutineforimplementingheapify. (Putelementsof'a'inheaporder,in-place) procedureheapify(a,count)is (startisassignedtheindexin'a'ofthelastparentnode) (thelastelementina0-basedarrayisatindexcount-1;findtheparentofthatelement) start←iParent(count-1) whilestart≥0do (siftdownthenodeatindex'start'totheproperplacesuchthatallnodesbelow thestartindexareinheaporder) siftDown(a,start,count-1) (gotothenextparentnode) start←start-1 (aftersiftingdowntherootallnodes/elementsareinheaporder) (Repairtheheapwhoserootelementisatindex'start',assumingtheheapsrootedatitschildrenarevalid) proceduresiftDown(a,start,end)is root←start whileiLeftChild(root)≤enddo(Whiletheroothasatleastonechild) child←iLeftChild(root)(Leftchildofroot) swap←root(Keepstrackofchildtoswapwith) ifa[swap]start parent :=iParent(child) ifa[parent]0do (a[0]istherootandlargestvalue.Theswapmovesitinfrontofthesortedelements.) swap(a[end],a[0]) (rebuildtheheapusingsiftUpaftertheswapruinstheheapproperty) heapify(a,end) (reducetheheapsizebyone) end←end-1 Variations[edit] Floyd'sheapconstruction[edit] Themostimportantvariationtothebasicalgorithm,whichisincludedinallpracticalimplementations,isaheap-constructionalgorithmbyFloydwhichrunsinO(n)timeandusessiftdownratherthansiftup,avoidingtheneedtoimplementsiftupatall. Ratherthanstartingwithatrivialheapandrepeatedlyaddingleaves,Floyd'salgorithmstartswiththeleaves,observingthattheyaretrivialbutvalidheapsbythemselves,andthenaddsparents.Startingwithelementn/2andworkingbackwards,eachinternalnodeismadetherootofavalidheapbysiftingdown.Thelaststepissiftingdownthefirstelement,afterwhichtheentirearrayobeystheheapproperty. Theworst-casenumberofcomparisonsduringtheFloyd'sheap-constructionphaseofheapsortisknowntobeequalto2n−2s2(n)−e2(n),wheres2(n)isthenumberof1bitsinthebinaryrepresentationofnande2(n)isnumberoftrailing0bits.[5] ThestandardimplementationofFloyd'sheap-constructionalgorithmcausesalargenumberofcachemissesoncethesizeofthedataexceedsthatoftheCPUcache.[6]: 87 Muchbetterperformanceonlargedatasetscanbeobtainedbymergingindepth-firstorder,combiningsubheapsassoonaspossible,ratherthancombiningallsubheapsononelevelbeforeproceedingtotheoneabove.[7][8] Bottom-upheapsort[edit] Bottom-upheapsortisavariantwhichreducesthenumberofcomparisonsrequiredbyasignificantfactor.Whileordinaryheapsortrequires2nlog2n+O(n)comparisonsworst-caseandonaverage,[9]thebottom-upvariantrequiresnlog2n+O(1)comparisonsonaverage,[9]and1.5nlog2n+O(n)intheworstcase.[10] Ifcomparisonsarecheap(e.g.integerkeys)thenthedifferenceisunimportant,[11]astop-downheapsortcomparesvaluesthathavealreadybeenloadedfrommemory.If,however,comparisonsrequireafunctioncallorothercomplexlogic,thenbottom-upheapsortisadvantageous. ThisisaccomplishedbyimprovingthesiftDownprocedure.Thechangeimprovesthelinear-timeheap-buildingphasesomewhat,[12]butismoresignificantinthesecondphase.Likeordinaryheapsort,eachiterationofthesecondphaseextractsthetopoftheheap,a[0],andfillsthegapitleaveswitha[end],thensiftsthislatterelementdowntheheap.Butthiselementcomesfromthelowestleveloftheheap,meaningitisoneofthesmallestelementsintheheap,sothesift-downwilllikelytakemanystepstomoveitbackdown.[13]Inordinaryheapsort,eachstepofthesift-downrequirestwocomparisons,tofindtheminimumofthreeelements:thenewnodeanditstwochildren. Bottom-upheapsortinsteadfindsthepathoflargestchildrentotheleaflevelofthetree(asifitwereinserting−∞)usingonlyonecomparisonperlevel.Putanotherway,itfindsaleafwhichhasthepropertythatitandallofitsancestorsaregreaterthanorequaltotheirsiblings.(Intheabsenceofequalkeys,thisleafisunique.)Then,fromthisleaf,itsearchesupward(usingonecomparisonperlevel)forthecorrectpositioninthatpathtoinserta[end].Thisisthesamelocationasordinaryheapsortfinds,andrequiresthesamenumberofexchangestoperformtheinsert,butfewercomparisonsarerequiredtofindthatlocation.[10] Becauseitgoesallthewaytothebottomandthencomesbackup,itiscalledheapsortwithbouncebysomeauthors.[14] functionleafSearch(a,i,end)is j←i whileiRightChild(j)≤enddo (Determinewhichofj'stwochildrenisthegreater) ifa[iRightChild(j)]>a[iLeftChild(j)]then j←iRightChild(j) else j←iLeftChild(j) (Atthelastlevel,theremightbeonlyonechild) ifiLeftChild(j)≤endthen j←iLeftChild(j) returnj ThereturnvalueoftheleafSearchisusedinthemodifiedsiftDownroutine:[10] proceduresiftDown(a,i,end)is j←leafSearch(a,i,end) whilea[i]>a[j]do j←iParent(j) x←a[j] a[j]←a[i] whilej>ido swapx,a[iParent(j)] j←iParent(j) Bottom-upheapsortwasannouncedasbeatingquicksort(withmedian-of-threepivotselection)onarraysofsize≥16000.[9] A2008re-evaluationofthisalgorithmshowedittobenofasterthanordinaryheapsortforintegerkeys,presumablybecausemodernbranchpredictionnullifiesthecostofthepredictablecomparisonswhichbottom-upheapsortmanagestoavoid.[11] Afurtherrefinementdoesabinarysearchinthepathtotheselectedleaf,andsortsinaworstcaseof(n+1)(log2(n+1)+log2log2(n+1)+1.82)+O(log2n)comparisons,approachingtheinformation-theoreticlowerboundofnlog2n−1.4427ncomparisons.[15] Avariantwhichusestwoextrabitsperinternalnode(n−1bitstotalforann-elementheap)tocacheinformationaboutwhichchildisgreater(twobitsarerequiredtostorethreecases:left,right,andunknown)[12]useslessthannlog2n+1.1ncompares.[16] Othervariations[edit] Ternaryheapsortusesaternaryheapinsteadofabinaryheap;thatis,eachelementintheheaphasthreechildren.Itismorecomplicatedtoprogram,butdoesaconstantnumberoftimesfewerswapandcomparisonoperations.Thisisbecauseeachsift-downstepinaternaryheaprequiresthreecomparisonsandoneswap,whereasinabinaryheaptwocomparisonsandoneswaparerequired.Twolevelsinaternaryheapcover32=9elements,doingmoreworkwiththesamenumberofcomparisonsasthreelevelsinthebinaryheap,whichonlycover23=8.[citationneeded]Thisisprimarilyofacademicinterest,orasastudentexercise,[17]astheadditionalcomplexityisnotworththeminorsavings,andbottom-upheapsortbeatsboth. Memory-optimizedheapsort[6]: 87 improvesheapsort'slocalityofreferencebyincreasingthenumberofchildrenevenmore.Thisincreasesthenumberofcomparisons,butbecauseallchildrenarestoredconsecutivelyinmemory,reducesthenumberofcachelinesaccessedduringheaptraversal,anetperformanceimprovement. Out-of-placeheapsort[18][19][13]improvesonbottom-upheapsortbyeliminatingtheworstcase,guaranteeingnlog2n+O(n)comparisons.Whenthemaximumistaken,ratherthanfillthevacatedspacewithanunsorteddatavalue,fillitwitha−∞sentinelvalue,whichnever"bounces"backup.Itturnsoutthatthiscanbeusedasaprimitiveinanin-place(andnon-recursive)"QuickHeapsort"algorithm.[20]First,youperformaquicksort-likepartitioningpass,butreversingtheorderofthepartitioneddatainthearray.Suppose(withoutlossofgenerality)thatthesmallerpartitionistheonegreaterthanthepivot,whichshouldgoattheendofthearray,butourreversedpartitioningstepplacesitatthebeginning.Formaheapoutofthesmallerpartitionanddoout-of-placeheapsortonit,exchangingtheextractedmaximawithvaluesfromtheendofthearray.Thesearelessthanthepivot,meaninglessthananyvalueintheheap,soserveas−∞sentinelvalues.Oncetheheapsortiscomplete(andthepivotmovedtojustbeforethenow-sortedendofthearray),theorderofthepartitionshasbeenreversed,andthelargerpartitionatthebeginningofthearraymaybesortedinthesameway.(Becausethereisnonon-tailrecursion,thisalsoeliminatesquicksort'sO(logn)stackusage.) Thesmoothsortalgorithm[21]isavariationofheapsortdevelopedbyEdsgerW.Dijkstrain1981.Likeheapsort,smoothsort'supperboundisO(nlogn).TheadvantageofsmoothsortisthatitcomesclosertoO(n)timeiftheinputisalreadysortedtosomedegree,whereasheapsortaveragesO(nlogn)regardlessoftheinitialsortedstate.Duetoitscomplexity,smoothsortisrarelyused.[citationneeded] LevcopoulosandPetersson[22]describeavariationofheapsortbasedonaheapofCartesiantrees.First,aCartesiantreeisbuiltfromtheinputinO(n)time,anditsrootisplacedina1-elementbinaryheap.Thenwerepeatedlyextracttheminimumfromthebinaryheap,outputthetree'srootelement,andadditsleftandrightchildren(ifany)whicharethemselvesCartesiantrees,tothebinaryheap.[23]Astheyshow,iftheinputisalreadynearlysorted,theCartesiantreeswillbeveryunbalanced,withfewnodeshavingleftandrightchildren,resultinginthebinaryheapremainingsmall,andallowingthealgorithmtosortmorequicklythanO(nlogn)forinputsthatarealreadynearlysorted. Severalvariantssuchasweakheapsortrequirenlog2n+O(1)comparisonsintheworstcase,closetothetheoreticalminimum,usingoneextrabitofstatepernode.Whilethisextrabitmakesthealgorithmsnottrulyin-place,ifspaceforitcanbefoundinsidetheelement,thesealgorithmsaresimpleandefficient,[7]: 40 butstillslowerthanbinaryheapsifkeycomparisonsarecheapenough(e.g.integerkeys)thataconstantfactordoesnotmatter.[24] Katajainen's"ultimateheapsort"requiresnoextrastorage,performsnlog2n+O(1)comparisons,andasimilarnumberofelementmoves.[25]Itis,however,evenmorecomplexandnotjustifiedunlesscomparisonsareveryexpensive. Comparisonwithothersorts[edit] Heapsortprimarilycompeteswithquicksort,anotherveryefficientgeneralpurposein-placecomparison-basedsortalgorithm. Heapsort'sprimaryadvantagesareitssimple,non-recursivecode,minimalauxiliarystoragerequirement,andreliablygoodperformance:itsbestandworstcasesarewithinasmallconstantfactorofeachother,andofthetheoreticallowerboundoncomparisonsorts.WhileitcannotdobetterthanO(nlogn)forpre-sortedinputs,itdoesnotsufferfromquicksort'sO(n2)worstcase,either.(Thelattercanbeavoidedwithcarefulimplementation,butthatmakesquicksortfarmorecomplex,andoneofthemostpopularsolutions,introsort,usesheapsortforthepurpose.) Itsprimarydisadvantagesareitspoorlocalityofreferenceanditsinherentlyserialnature;theaccessestotheimplicittreearewidelyscatteredandmostlyrandom,andthereisnostraightforwardwaytoconvertittoaparallelalgorithm. Thismakesitpopularinembeddedsystems,real-timecomputing,andsystemsconcernedwithmaliciouslychoseninputs,[26]suchastheLinuxkernel.[27]Itisalsoagoodchoiceforanyapplicationwhichdoesnotexpecttobebottleneckedonsorting. Awell-implementedquicksortisusually2–3timesfasterthanheapsort.[6][28]Althoughquicksortrequiresfewercomparisons,thisisaminorfactor.(Resultsclaimingtwiceasmanycomparisonsaremeasuringthetop-downversion;see§ Bottom-upheapsort.)Themainadvantageofquicksortisitsmuchbetterlocalityofreference:partitioningisalinearscanwithgoodspatiallocality,andtherecursivesubdivisionhasgoodtemporallocality.Withadditionaleffort,quicksortcanalsobeimplementedinmostlybranch-freecode,andmultipleCPUscanbeusedtosortsubpartitionsinparallel.Thus,quicksortispreferredwhentheadditionalperformancejustifiestheimplementationeffort. TheothermajorO(nlogn)sortingalgorithmismergesort,butthatrarelycompetesdirectlywithheapsortbecauseitisnotin-place.Mergesort'srequirementforΩ(n)extraspace(roughlyhalfthesizeoftheinput)isusuallyprohibitiveexceptinthesituationswheremergesorthasaclearadvantage: Whenastablesortisrequired Whentakingadvantageof(partially)pre-sortedinput Sortinglinkedlists(inwhichcasemergesortrequiresminimalextraspace) Parallelsorting;mergesortparallelizesevenbetterthanquicksortandcaneasilyachieveclosetolinearspeedup Externalsorting;mergesorthasexcellentlocalityofreference Example[edit] Let{6,5,3,1,8,7,2,4}bethelistthatwewanttosortfromthesmallesttothelargest.(NOTE,for'BuildingtheHeap'step:Largernodesdon'tstaybelowsmallernodeparents.Theyareswappedwithparents,andthenrecursivelycheckedifanotherswapisneeded,tokeeplargernumbersabovesmallernumbersontheheapbinarytree.) Anexampleonheapsort. Buildtheheap[edit] Heap Newlyaddedelement Swapelements NULL 6 6 5 6,5 3 6,5,3 1 6,5,3,1 8 6,5,3,1,8 5,8 6,8,3,1,5 6,8 8,6,3,1,5 7 8,6,3,1,5,7 3,7 8,6,7,1,5,3 2 8,6,7,1,5,3,2 4 8,6,7,1,5,3,2,4 1,4 8,6,7,4,5,3,2,1 Sorting[edit] Heap Swapelements Deleteelement Sortedarray Details 8,6,7,4,5,3,2,1 8,1 Swap8and1inordertodelete8fromheap 1,6,7,4,5,3,2,8 8 Delete8fromheapandaddtosortedarray 1,6,7,4,5,3,2 1,7 8 Swap1and7astheyarenotinorderintheheap 7,6,1,4,5,3,2 1,3 8 Swap1and3astheyarenotinorderintheheap 7,6,3,4,5,1,2 7,2 8 Swap7and2inordertodelete7fromheap 2,6,3,4,5,1,7 7 8 Delete7fromheapandaddtosortedarray 2,6,3,4,5,1 2,6 7,8 Swap2and6astheyarenotinorderintheheap 6,2,3,4,5,1 2,5 7,8 Swap2and5astheyarenotinorderintheheap 6,5,3,4,2,1 6,1 7,8 Swap6and1inordertodelete6fromheap 1,5,3,4,2,6 6 7,8 Delete6fromheapandaddtosortedarray 1,5,3,4,2 1,5 6,7,8 Swap1and5astheyarenotinorderintheheap 5,1,3,4,2 1,4 6,7,8 Swap1and4astheyarenotinorderintheheap 5,4,3,1,2 5,2 6,7,8 Swap5and2inordertodelete5fromheap 2,4,3,1,5 5 6,7,8 Delete5fromheapandaddtosortedarray 2,4,3,1 2,4 5,6,7,8 Swap2and4astheyarenotinorderintheheap 4,2,3,1 4,1 5,6,7,8 Swap4and1inordertodelete4fromheap 1,2,3,4 4 5,6,7,8 Delete4fromheapandaddtosortedarray 1,2,3 1,3 4,5,6,7,8 Swap1and3astheyarenotinorderintheheap 3,2,1 3,1 4,5,6,7,8 Swap3and1inordertodelete3fromheap 1,2,3 3 4,5,6,7,8 Delete3fromheapandaddtosortedarray 1,2 1,2 3,4,5,6,7,8 Swap1and2astheyarenotinorderintheheap 2,1 2,1 3,4,5,6,7,8 Swap2and1inordertodelete2fromheap 1,2 2 3,4,5,6,7,8 Delete2fromheapandaddtosortedarray 1 1 2,3,4,5,6,7,8 Delete1fromheapandaddtosortedarray 1,2,3,4,5,6,7,8 Completed Notes[edit] ^Skiena,Steven(2008)."SearchingandSorting".TheAlgorithmDesignManual.Springer.p. 109.doi:10.1007/978-1-84800-070-4_4.ISBN 978-1-84800-069-8.[H]eapsortisnothingbutanimplementationofselectionsortusingtherightdatastructure. ^Williams1964 ^abBrass,Peter(2008).AdvancedDataStructures.CambridgeUniversityPress.p. 209.ISBN 978-0-521-88037-4. ^"PriorityQueues".Archivedfromtheoriginalon9September2020.Retrieved10September2020. ^Suchenek,MarekA.(2012)."ElementaryYetPreciseWorst-CaseAnalysisofFloyd'sHeap-ConstructionProgram".FundamentaInformaticae.120(1):75–92.doi:10.3233/FI-2012-751. ^abcLaMarca,Anthony;Ladner,RichardE.(April1999)."TheInfluenceofCachesonthePerformanceofSorting".JournalofAlgorithms.31(1):66–104.CiteSeerX 10.1.1.456.3616.doi:10.1006/jagm.1998.0985.S2CID 206567217.Seeparticularlyfigure9conp.98. ^abBojesen,Jesper;Katajainen,Jyrki;Spork,Maz(2000)."PerformanceEngineeringCaseStudy:HeapConstruction"(PostScript).ACMJournalofExperimentalAlgorithmics.5(15):15–es.CiteSeerX 10.1.1.35.3248.doi:10.1145/351827.384257.S2CID 30995934.AlternatePDFsource. ^Chen,Jingsen;Edelkamp,Stefan;Elmasry,Amr;Katajainen,Jyrki(27–31August2012)."In-placeHeapConstructionwithOptimizedComparisons,Moves,andCacheMisses"(PDF).MathematicalFoundationsofComputerScience2012.37thinternationalconferenceonMathematicalFoundationsofComputerScience.LectureNotesinComputerScience.Vol. 7464.Bratislava,Slovakia.pp. 259–270.doi:10.1007/978-3-642-32589-2_25.ISBN 978-3-642-32588-5.S2CID 1462216.Archivedfromtheoriginal(PDF)on29December2016.SeeparticularlyFig.3. ^abcWegener,Ingo(13September1993)."BOTTOM-UPHEAPSORT,anewvariantofHEAPSORTbeating,onanaverage,QUICKSORT(ifnisnotverysmall)"(PDF).TheoreticalComputerScience.118(1):81–98.doi:10.1016/0304-3975(93)90364-y.Althoughthisisareprintofworkfirstpublishedin1990(attheMathematicalFoundationsofComputerScienceconference),thetechniquewaspublishedbyCarlssonin1987.[15] ^abcFleischer,Rudolf(February1994)."AtightlowerboundfortheworstcaseofBottom-Up-Heapsort"(PDF).Algorithmica.11(2):104–115.doi:10.1007/bf01182770.hdl:11858/00-001M-0000-0014-7B02-C.S2CID 21075180.AlsoavailableasFleischer,Rudolf(April1991).AtightlowerboundfortheworstcaseofBottom-Up-Heapsort(PDF)(Technicalreport).MPI-INF.MPI-I-91-104. ^abMehlhorn,Kurt;Sanders,Peter(2008)."PriorityQueues"(PDF).AlgorithmsandDataStructures:TheBasicToolbox.Springer.p. 142.ISBN 978-3-540-77977-3. ^abMcDiarmid,C.J.H.;Reed,B.A.(September1989)."Buildingheapsfast"(PDF).JournalofAlgorithms.10(3):352–365.doi:10.1016/0196-6774(89)90033-3. ^abMacKay,DavidJ.C.(December2005)."Heapsort,Quicksort,andEntropy".Retrieved12February2021. ^Moret,Bernard;Shapiro,HenryD.(1991)."8.6Heapsort".AlgorithmsfromPtoNPVolume1:DesignandEfficiency.Benjamin/Cummings.p. 528.ISBN 0-8053-8008-6.Forlackofabetternamewecallthisenhancedprogram'heapsortwithbounce.' ^abCarlsson,Scante(March1987)."Avariantofheapsortwithalmostoptimalnumberofcomparisons"(PDF).InformationProcessingLetters.24(4):247–250.doi:10.1016/0020-0190(87)90142-6.S2CID 28135103.Archivedfromtheoriginal(PDF)on27December2016. ^Wegener,Ingo(March1992)."TheworstcasecomplexityofMcDiarmidandReed'svariantofBOTTOM-UPHEAPSORTislessthann log n+1.1n".InformationandComputation.97(1):86–96.doi:10.1016/0890-5401(92)90005-Z. ^Tenenbaum,AaronM.;Augenstein,MosheJ.(1981)."Chapter8:Sorting".DataStructuresUsingPascal.p. 405.ISBN 0-13-196501-8.Writeasortingroutinesimilartotheheapsortexceptthatitusesaternaryheap. ^Cantone,Domenico;Concotti,Gianluca(1–3March2000).QuickHeapsort,anefficientmixofclassicalsortingalgorithms.4thItalianConferenceonAlgorithmsandComplexity.LectureNotesinComputerScience.Vol. 1767.Rome.pp. 150–162.ISBN 3-540-67159-5. ^Cantone,Domenico;Concotti,Gianluca(August2002)."QuickHeapsort,anefficientmixofclassicalsortingalgorithms"(PDF).TheoreticalComputerScience.285(1):25–42.doi:10.1016/S0304-3975(01)00288-2.Zbl 1016.68042. ^Diekert,Volker;Weiß,Armin(August2016)."QuickHeapsort:Modificationsandimprovedanalysis".TheoryofComputingSystems.59(2):209–230.arXiv:1209.4214.doi:10.1007/s00224-015-9656-y.S2CID 792585. ^Dijkstra,EdsgerW.Smoothsort–analternativetosortinginsitu(EWD-796a)(PDF).E.W.DijkstraArchive.CenterforAmericanHistory,UniversityofTexasatAustin.(transcription) ^Levcopoulos,Christos;Petersson,Ola(1989)."Heapsort—AdaptedforPresortedFiles".WADS'89:ProceedingsoftheWorkshoponAlgorithmsandDataStructures.LectureNotesinComputerScience.Vol. 382.London,UK:Springer-Verlag.pp. 499–509.doi:10.1007/3-540-51542-9_41.ISBN 978-3-540-51542-5.Heapsort—Adaptedforpresortedfiles(Q56049336). ^Schwartz,Keith(27December2010)."CartesianTreeSort.hh".ArchiveofInterestingCode.Retrieved5March2019. ^Katajainen,Jyrki(23September2013).Seekingforthebestpriorityqueue:Lessonslearnt.AlgorithmEngineering(Seminar13391).Dagstuhl.pp. 19–20,24. ^Katajainen,Jyrki(2–3February1998).TheUltimateHeapsort.Computing:the4thAustralasianTheorySymposium.AustralianComputerScienceCommunications.Vol. 20,no. 3.Perth.pp. 87–96. ^Morris,John(1998)."ComparingQuickandHeapSorts".DataStructuresandAlgorithms(Lecturenotes).UniversityofWesternAustralia.Retrieved12February2021. ^https://github.com/torvalds/linux/blob/master/lib/sort.cLinuxkernelsource ^Maus,Arne(14May2014)."Sortingbygeneratingthesortingpermutation,andtheeffectofcachingonsorting".SeeFig.1onp.6. References[edit] Williams,J.W.J.(1964)."Algorithm232–Heapsort".CommunicationsoftheACM.7(6):347–348.doi:10.1145/512274.512284. Floyd,RobertW.(1964)."Algorithm245–Treesort3".CommunicationsoftheACM.7(12):701.doi:10.1145/355588.365103.S2CID 52864987. Carlsson,Svante(1987)."Average-caseresultsonheapsort".BITNumericalMathematics.27(1):2–17.doi:10.1007/bf01937350.S2CID 31450060. Knuth,Donald(1997)."§5.2.3,SortingbySelection".TheArtofComputerProgramming.Vol. 3:SortingandSearching(3rd ed.).Addison-Wesley.pp. 144–155.ISBN 978-0-201-89685-5. Cormen,ThomasH.;Leiserson,CharlesE.;Rivest,RonaldL.;Stein,Clifford(2001).IntroductiontoAlgorithms(2nd ed.).MITPressandMcGraw-Hill.ISBN 0-262-03293-7.Chapters6and7Respectively:HeapsortandPriorityQueues APDFofDijkstra'soriginalpaperonSmoothsort HeapsandHeapsortTutorialbyDavidCarlson,St.VincentCollege Externallinks[edit] TheWikibookAlgorithmimplementationhasapageonthetopicof:Heapsort AnimatedSortingAlgorithms:HeapSortattheWaybackMachine(archived6March2015)–graphicaldemonstration CoursewareonHeapsortfromUniv.Oldenburg–Withtext,animationsandinteractiveexercises NIST'sDictionaryofAlgorithmsandDataStructures:Heapsort Heapsortimplementedin12languages SortingrevisitedbyPaulHsieh APowerPointpresentationdemonstratinghowHeapsortworksthatisforeducators. OpenDataStructures–Section11.1.3–Heap-Sort,PatMorin vteSortingalgorithmsTheory Computationalcomplexitytheory BigOnotation Totalorder Lists Inplacement Stability Comparisonsort Adaptivesort Sortingnetwork Integersorting X+Ysorting Transdichotomousmodel Quantumsort Exchangesorts Bubblesort Cocktailshakersort Odd–evensort Combsort Gnomesort Proportionextendsort Quicksort Slowsort Stoogesort Bogosort Selectionsorts Selectionsort Heapsort Smoothsort Cartesiantreesort Tournamentsort Cyclesort Weak-heapsort Insertionsorts Insertionsort Shellsort Splaysort Treesort Librarysort Patiencesorting Mergesorts Mergesort Cascademergesort Oscillatingmergesort Polyphasemergesort Distributionsorts Americanflagsort Beadsort Bucketsort Burstsort Countingsort Interpolationsort Pigeonholesort Proxmapsort Radixsort Flashsort Concurrentsorts Bitonicsorter Batcherodd–evenmergesort Pairwisesortingnetwork Samplesort Hybridsorts Blockmergesort Kirkpatrick-Reischsort Timsort Introsort Spreadsort Merge-insertionsort Other Topologicalsorting Pre-topologicalorder Pancakesorting Spaghettisort Retrievedfrom"https://en.wikipedia.org/w/index.php?title=Heapsort&oldid=1094605728" Categories:ComparisonsortsHeaps(datastructures)SortingalgorithmsHiddencategories:ArticleswithshortdescriptionShortdescriptionisdifferentfromWikidataUsedmydatesfromMarch2022AllarticleswithunsourcedstatementsArticleswithunsourcedstatementsfromSeptember2014ArticleswithunsourcedstatementsfromNovember2016CS1:longvolumevalueWebarchivetemplatewaybacklinksArticleswithexamplepseudocode Navigationmenu Personaltools NotloggedinTalkContributionsCreateaccountLogin Namespaces ArticleTalk English Views ReadEditViewhistory More Search Navigation MainpageContentsCurrenteventsRandomarticleAboutWikipediaContactusDonate Contribute HelpLearntoeditCommunityportalRecentchangesUploadfile Tools WhatlinkshereRelatedchangesUploadfileSpecialpagesPermanentlinkPageinformationCitethispageWikidataitem Print/export DownloadasPDFPrintableversion Inotherprojects WikimediaCommons Languages العربيةAzərbaycancaবাংলাБългарскиCatalàČeštinaDeutschEestiEspañolفارسیFrançais한국어Հայերենहिन्दीÍslenskaItalianoעבריתLëtzebuergeschLietuviųMagyarമലയാളംNederlands日本語NorskbokmålPolskiPortuguêsРусскийSimpleEnglishSlovenščinaСрпски/srpskiSuomiSvenskaไทยTürkçeУкраїнськаTiếngViệt中文 Editlinks
延伸文章資訊
- 1Heapsort - Wikipedia
Heapsort can be thought of as an improved selection sort: like selection sort, heapsort divides i...
- 2Heap Sort (With Code in Python, C++, Java and C) - Programiz
Complexity
- 3Heapsort Algorithm - Interview Cake
Heap sort runs in O ( n lg ( n ) ) O(n\lg(n)) O(nlg(n)) time, which scales well as n n n grows....
- 4Heap Sort | Brilliant Math & Science Wiki
Heapsort is a comparison-based sorting algorithm that uses a binary heap data structure. Like mer...
- 5Heapsort – Algorithm, Source Code, Time Complexity