02-Analysis of Insertion Sort - cs.albany.edupetko/classes/FALL16-CSI403...Insertion sort growth...
Transcript of 02-Analysis of Insertion Sort - cs.albany.edupetko/classes/FALL16-CSI403...Insertion sort growth...
403:AlgorithmsandDataStructures
AnalysisofInsertionSortFall2016UAlbany
ComputerScience
Tune-inexercise
• Whatisalgorithmanalysis?–Meanstopredicttheresourcesneededforanalgorithmexecution.
• Whatresourcesareweconcernedwith?– Runningtimeandmemory
• Whydoweneedsuchresourceprediction?– Tobeabletocomparealgorithms– Tobeabletoprovisionresourcesforalgorithmexecution
Exampleofinsertionsortonaninstance
• Whichisthealgorithm?• Whichistheinput?• Whichistheoutput?• Whatistheinstance?
Thealgorithm
Theinput
Theoutput
<5,2,4,6,1,3>
Exampleofinsertionsortonaninstance
Takeaminutetothinkonyourownofwhatishappeningateachstep.
Insertionsort(pseudocode)
Thisstepcanbereachedwheni=0orifA[i]≤key.Inbothcaseskeyisplaceds.t. A[1…i]issorted
Inputarrayis1-based
j indexesthewhole
array
iindexesthesortedsequence
Insertionsort-- analysis
• Recallthateachprimitiveoperationtakesconstanttime
• Assumetherearen numbersintheinput
• c1,c2,andc3 areconstantsanddonotdependonn
c1
c2c3
Insertionsort-- analysis
• Assumetherearen numbersintheinput
c2
c1
c3
Whatisthetimeneededforthealgorithmexecution?
Insertionsort-- analysis• Assumetherearen numbersintheinput
• While loopisexecutedatmostj-1 timesforagiven j,sotimespentinloopisatmost(j-1)c2
• AnyiterationoftheouterFor looptakesatmostc1 +(j-1)c2+c3
• Theoverallrunningtimeofinsertionsortis∑ c1+(j-1)c2+c3𝒏𝒋$𝟐 =d1n2 +d2n+d3
c2
c1
c3
Wasouranalysistoopessimistic?
• Wejustperformedaworst-caseanalysisofinsertionsort,whichgaveusanupperboundoftherunningtime.
• Wasouranalysistoopessimistic?Inotherwords,arethereinstancesthatwillcausethealgorithmtorunwithquadratictimeinn?– Theworst-caseinstanceisareverse-sortedsequencea1,a2,…,an suchthata1>a2>…>an
• Sinceworst-casesequenceexists,wesaythatouranalysisis“tight”and”notpessimistic”.
Insertionsortgrowthrate
• Considerinsertionsort’srunningtimeasthefunctiond1n2 +d2n+d3– Thedominantpartofthisfunctionisn2 (i.e.asnbecomeslarge,n2 growsmuchfasterthann)
– Thus,thegrowthrateoftherunningtimeisdeterminedbythen2 term
–WeexpressthisasO(n2)(a.k.a.“big-oh”notation*)–Wecomparealgorithmsintermsoftheirrunningtime
*Tobeformallydefinedlater
Algorithmcomparison• Whichalgorithmisbetter?
– Weanswerthisquestionbycomparingalgorithms’O()runningtimes.
• Example:ComparealgorithmAandB.Whichoneisbetter?– AlgorithmA:O(n2)– AlgorithmB:O(nlog2(n))
ByCmglee - Ownwork,CCBY-SA4.0,https://commons.wikimedia.org/w/index.php?curid=50321072
• Bismoreefficient.• Intuitivelyn2 growsfaster• Wemightbewrongforsmallinstancesbutwhen nislargeBwillbefaster
• Largesizescomeaboutveryoften(Facebookhas100sofmillionsofusers)
Announcements
• ReadthroughChapters1and2inthebook• Homework1posted,DueonSep7