




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 破碎搅拌机市场发展分析及行业投资战略研究报告2025-2028版
- 房屋拆迁居间代理合同范本
- 车辆买卖居间与车辆改装升级服务合同
- 大型女职工活动方案
- 大型海洋展活动方案
- 大学组织活动活动方案
- 大手牵小手活动方案
- 地摊低价活动方案
- 垃圾可回收日活动方案
- 外卖盒饭活动方案
- 【课件】新高三启动主题班会:启航高三逐梦未来
- 长鑫存储在线试题及答案
- 小学劳动教育校本课程开发实践与研究
- 森林草原防火 无人机巡查技术规范 编制说明
- 2025-2030中国发泡聚苯乙烯泡沫行业市场现状供需分析及投资评估规划分析研究报告
- 不寐的中医护理常规
- 《能源的科普讲解》课件
- 天一大联考·天一小高考2024-2025学年(下)高三第四次考试政治试题及答案
- 2025年安庆桐城经开区建设投资集团有限公司招聘12人笔试参考题库附带答案详解
- 2025-2030中国药食同源行业市场运行分析及市场前景预测研究报告
- 2024年杭州地铁科技有限公司招聘笔试真题
评论
0/150
提交评论