![ADA分治法快速排序_第1頁](http://file4.renrendoc.com/view/8282c0e90d7f5cbf425d3a2658306cf6/8282c0e90d7f5cbf425d3a2658306cf61.gif)
![ADA分治法快速排序_第2頁](http://file4.renrendoc.com/view/8282c0e90d7f5cbf425d3a2658306cf6/8282c0e90d7f5cbf425d3a2658306cf62.gif)
![ADA分治法快速排序_第3頁](http://file4.renrendoc.com/view/8282c0e90d7f5cbf425d3a2658306cf6/8282c0e90d7f5cbf425d3a2658306cf63.gif)
![ADA分治法快速排序_第4頁](http://file4.renrendoc.com/view/8282c0e90d7f5cbf425d3a2658306cf6/8282c0e90d7f5cbf425d3a2658306cf64.gif)
![ADA分治法快速排序_第5頁](http://file4.renrendoc.com/view/8282c0e90d7f5cbf425d3a2658306cf6/8282c0e90d7f5cbf425d3a2658306cf65.gif)
版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
2023/2/51ReviewoflastclassDivideandConquertechniqueThemergesortalgorithmanditsbest-case,worst-caseandaverage-caseanalysis2023/2/52DivideAndConquer(II)Chapter4ApplicationtosortingproblemQuicksort2023/2/53GoalsoftheLectureAttheendofthislecture,youshouldMastertheideaofquicksortalgorithmMasterthebest-case,worst-caseandaverage-caseanalysisofquicksortalgorithmUnderstandthedifferencebetweenmergesortandquicksort2023/2/54QuicksortAnothersortalgorithmexampletorevealtheessenceofdivide-and-conquertechniqueItsideacanbedescribedasfollows:Divide:PartitionthearrayA[p..r]intotwosubarraysA[p..q]andA[q+1..r]Invariant:AllelementsinA[p..q]arelessthanallelementsinA[q+1..r]Conquer:SortthetwosubarraysrecursivelyMerge:Unlikemergesort,nocombiningstep,twosubarraysformanalready-sortedarray2023/2/55QuicksortAlgorithmALGORITHMQuickSort(A,l,r)
//Sortsasubarraybyquicksort //Input:AsubarrayA[l…r]ofA[0…n-1],definedbyits // leftandrightindiceslandr //Output:SubarrayA[l…r]sortedinnondecreasingorder
if
l<r
s
←Partition(A,l,r)//sisasplitposition QuickSort(A,l,s-1) QuickSort(A,s+1,r)
end
if2023/2/56Clearly,alltheactiontakesplaceinthedivide
stepshouldbethefollowings:SelectapivotandrearrangesthearrayinplaceEndresult:TwosubarraysbeenseparatedbythepivotTheelementsinonesubarrayaresmallerthanthepivotTheelementsinanotherarelargerthanthepivotReturnstheindexofthe“pivot”elementseparatingthetwosubarraysHowdoyousupposeweimplementthis?Partition2023/2/57PartitionInWordsGivenanarrayA[0,…,n-1],wecanpartitionthearraylikethese:(1)Initial:selectanelementtoactasthe“pivot”(which?),letiandjindicatetheindexofsecondleftandrightelementswhichwillbeusedtocomparewiththepivot.(2)Scanfromleft:IncreaseiuntilA[i]greaterthanandequaltothepivot.(3)Scanfromright:DecreasejuntilA[j]smallerthanandequaltothepivot.(4)SwapA[i]andA[j](5)Repeat(2),(3)and(4)untilj≤i.(6)SwapA[i]andA[j],swapA[0]andA[j],returnj.2023/2/58PartitionexampleInitiallist{6,7,5,2,5,8}{6,7,5,2,5,8}{6,5,5,2,7,8}{6,5,5,2,7,8}Done!Quciksortisnotstable{6,7,5,2,5,8}{2,5,5}6{7,8}2023/2/59PartitionAlgorithm(I)ALGORITHMPartition1(A,l,r)
//Input:AsubarrayA[l…r]ofA[0…n-1],definedbyitsleft//andrightindiceslandr(l<r)//Output:ApartitionofA[l…r],withthesplitposition//returnedasthisfunction’svalue
p←A[l]
i←l;j←r+1
repeat
repeat
i←i+1untilA[i]≥p
repeat
j←j-1untilA[j]≤pswap(A[i],A[j]);
until
i≥j
swap(A[i],A[j])//undolastsi≥j
swap(A[l],A[j]
return
j
//jisthefinalindexofpivot
AnyProblem?2023/2/510PartitionAlgorithm(II)ALGORITHMPartition1(A,l,r)
//Input:AsubarrayA[l…r]ofA[0…n-1],definedbyitsleft//andrightindiceslandr(l<r)//Output:ApartitionofA[l…r],withthesplitposition//returnedasthisfunction’svalue
p←A[l];j←l
fori
←l+1tordo
ifA[i]≤
p
j←j+1
if
j≠iswap(A[j],A[i])
end
if
end
for swap(A[l],A[j])
return
j
//jisthefinalindexofpivot
Whynot“<“?2023/2/511QuicksortExample2023/2/512AnalyzingQuicksortWhatwillbethebestcaseforthealgorithm?Partitionisperfectlybalanced,thismeansthatthearrayisdividedintotwoequallengthsubarrays.Inthebestcase:Tbest(1)=0Tbest(n)=2Tbest(n/2)+n-1Whatdoestherecurrencerelationworkoutto?T(n)=(nlogn)2023/2/513AnalyzingQuicksortWhatwillbetheworstcaseforthealgorithm?PartitionisalwaysunbalancedWillanyparticularinputelicittheworstcase?Yes:Already-sortedinputIntheworstcase,Partitionwilldon-1comparisons,butcreateonepartitionthathasn-1elementsandtheotherwillhavenoelementsBecausewewindupjustreducingthepartitionbyoneelementeachtime,worstcaseisgivenby:T(1)=0T(n)=T(n-1)+n-1TherecurrencerelationworksouttoT(n)=(n2)2023/2/514ImprovingQuicksortTherealliabilityofquicksortisthatitrunsinO(n2)onalready-sortedinputDiscussestwosolutions:Randomizetheinputarray,ORPickarandompivotelementHowwillthesesolvetheproblem?ByinsuringthatnoparticularinputcanbechosentomakequicksortruninO(n2)time2023/2/515AnalyzingQuicksort:AverageCaseAssumingrandominput,average-caserunningtimeismuchclosertoΘ(nlogn)thanO(n2)First,amoreintuitiveexplanation/example:Supposethatpartitionalwaysproducesa9-to-1split.Thislooksquiteunbalanced!Therecurrenceisthus: T(n)=T(9n/10)+T(n/10)+n-1
Howdeepwilltherecursiongo?(drawit)2023/2/516AnalyzingQuicksort:AverageCaseIntuitively,areal-liferunofquicksortwillproduceamixof“bad”and“good”splitsRandomlydistributedamongtherecursiontreePretendforintuitionthattheyalternatebetweenbest-case(n/2:n/2)andworst-case(n-1:0)Whathappensifwebad-splitrootnode,thengood-splittheresultingsize(n-1)node?2023/2/517AnalyzingQuicksort:AverageCaseIntuitively,areal-liferunofquicksortwillproduceamixof“bad”and“good”splitsRandomlydistributedamongtherecursiontreePretendforintuitionthattheyalternatebetweenbest-case(n/2:n/2)andworst-case(n-1:0)Whathappensifwebad-splitrootnode,thengood-splittheresultingsize(n-1)node?Weendupwiththreesubarrays,size0,(n-1)/2,(n-1)/2Combinedcostofsplits=n-1+n-2=2n-3=O(n)Noworsethanifwehadgood-splittherootnode!2023/2/518AnalyzingQuicksort:AverageCaseIntuitively,theO(n)costofabadsplit
(or2or3badsplits)canbeabsorbed
intotheO(n)costofeachgoodsplitThusrunningtimeofalternatingbadandgoodsplitsisstillO(nlogn),withslightlyhigherconstantsHowcanwebemorerigorous?2023/2/519AnalyzingQuicksort:AverageCaseForsimplicity,assume:Allinputsdistinct(norepeats)Slightlydifferentpartitionprocedurepartitionaroundarandomelement,whichisnotincludedinsubarraysallsplits(0:n-1,1:n-2,2:n-3,…,n-1:0)equallylikelyWhatistheprobabilityofaparticularsplithappening?Answer:1/n2023/2/520AnalyzingQuicksort:AverageCaseSopartitiongeneratessplits
(0:n-1,1:n-2,2:n-3,…,n-2:1,n-1:0)
eachwithprobability1/nIfT(n)istheexpectedrunningtime,Whatiseachtermunderthesummationfor?Whatisthe(n)termfor?
2023/2/521AnalyzingQuicksort:AverageCaseSo…2023/2/522AnalyzingQuicksort:AverageCaseWecansolvethisrecurrenceusingthedreadedsubstitutionmethodGuesstheanswerAssumethattheinductivehypothesisholdsSubstituteitinforsomevalue<nProvethatitfollowsforn2023/2/523AnalyzingQuicksort:AverageCaseWecansolvethisrecurrenceusingthedreadedsubstitutionmethodGuesstheanswerWhat’stheanswer?AssumethattheinductivehypothesisholdsSubstituteitinforsomevalue<nProvethatitfollowsforn2023/2/524AnalyzingQuicksort:AverageCaseWecansolvethisrecurrenceusingthedreadedsubstitutionmethodGuesstheanswerT(n)=Θ(nlogn)AssumethattheinductivehypothesisholdsSubstituteitinforsomevalue<nProvethatitfollowsforn2023/2/525AnalyzingQuicksort:AverageCaseWecansolvethisrecurrenceusingthedreadedsubstitutionmethodGuesstheanswerT(n)=Θ(nlogn)AssumethattheinductivehypothesisholdsWhat’stheinductivehypothesis?Substituteitinforsomevalue<nProvethatitfollowsforn2023/2/526AnalyzingQuicksort:AverageCaseWecansolvethisrecurrenceusingthedreadedsubstitutionmethodGuesstheanswerT(n)=Θ(nlogn)AssumethattheinductivehypothesisholdsT(n)anlogn+bforsomeconstantsaandbSubstituteitinforsomevalue<nProvethatitfollowsforn2023/2/527AnalyzingQuicksort:AverageCaseWecansolvethisrecurrenceusingthedreadedsubstitutionmethodGuesstheanswerT(n)=Θ(nlogn)AssumethattheinductivehypothesisholdsT(n)anlogn+bforsomeconstantsaandbSubstituteitinforsomevalue<nWhatvalue?Provethatitfollowsforn2023/2/528AnalyzingQuicksort:AverageCaseWecansolvethisrecurrenceusingthedreadedsubstitutionmethodGuesstheanswerT(n)=Θ(nlogn)AssumethattheinductivehypothesisholdsT(n)anlogn+bforsomeconstantsaandbSubstituteitinforsomevalue<nThevaluekintherecurrenceProvethatitfollowsforn2023/2/529Whatarewedoinghere?AnalyzingQuicksort:AverageCaseTherecurrencetobesolvedWhatarewedoinghere?Whatarewedoinghere?PlugininductivehypothesisExpandoutthek=0case2b/nisjustaconstant,
sofolditinto(n)2023/2/530Whatarewedoinghere?Whatarewedoinghere?Evaluatethesummation:
b+b+…+b=b(n-1)TherecurrencetobesolvedSincen-1<n,2b(n-1)/n<2bAnalyzingQuicksort:AverageCaseWhatarewedoinghere?DistributethesummationThissummationgetsitsownsetofslideslater2023/2/531Howdidwedothis?Pickalargeenoughthat
an/4dominates(n)+b
Whatarewedoinghere?Remember,ourgoalistogetT(n)anlogn+bWhatthehell?We’llprovethislaterWhatarewedoinghere?Distributethe(2a/n)termTherecurrencetobesolvedAnalyzingQuicksort:AverageCase2023/2/532AnalyzingQuicksort:AverageCaseSoT(n)anlogn+bforcertainaandbThustheinductionholdsThusT(n)=Θ(nlogn)ThusquicksortrunsinΘ(nlogn)timeonaverage(phew!)Ohyeah,thesummation…2023/2/533Whatarewedoinghere?ThelogkinthesecondtermisboundedbylognTightlyBoundingoftheKeySummationWhatarewedoinghere?MovethelognoutsidethesummationWhatarewedoinghere?Splitthesummationforatighterbound2023/2/534ThesummationboundsofarTightlyBoundingoftheKeyS
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年度私人老板與家政服務(wù)人員專項用工合同
- 《語言學(xué)概論教案》課件
- 《幼兒散文欣賞》課件
- 二零二五年度物流配送信息化管理合同范本
- 《icu患者鎮(zhèn)靜管理》課件
- 天津2025年離婚協(xié)議書起草服務(wù)合同
- 美容儀器國際市場開拓代理合同(2025年度)
- 《顱內(nèi)腫瘤講義》課件
- 宿舍生活垃圾分類承包合同2025年度實施
- 銅產(chǎn)業(yè)發(fā)展背景與意義
- 胸外科講課全套
- 醫(yī)療器械GSP相關(guān)
- 2023年海南省公務(wù)員錄用考試《行測》真題卷及答案解析
- 電力工程施工售后保障方案
- 中國心力衰竭診斷和治療指南2024解讀(完整版)
- 多源數(shù)據(jù)整合
- 新人教版高中數(shù)學(xué)必修第二冊第六章平面向量及其應(yīng)用教案 (一)
- 校園招聘活動策劃方案(6篇)
- 期末 (試題) -2024-2025學(xué)年教科版(廣州)英語四年級上冊
- 解讀國有企業(yè)管理人員處分條例課件
- 湖南省長沙市一中2024-2025學(xué)年高一生物上學(xué)期期末考試試題含解析
評論
0/150
提交評論