ANALYSIS & DESIGN oF
‘AleoniTHM
Contents
UNIT:
Algorithms, Designing algoct
‘Asymptote notations...
Heap and heap sort, =
Introduction to divide and conquer technique, Analysis
‘design and comparison of various algorithms based on this
technique, example binary search, Merge sort, Guick sor,
‘Strassen's matrix mutipicatio,
ws, Analyzing algorithms,
UNIT
Study of Greedy strategy, Examples of greedy method ike
‘lima merge pattems, Huffman coding, minimum spanning
‘toes, Knapsack problem, job sequencing with deadlines,
single source shortest path algorihm.
nn S10
Nt:
Concept of dynamic programming, problems based on this
‘2pproach such as 0/1 knapsack, mattstage grenh, relly
sign, Floys-Wershall IQR nna (10910136
univ:
Backtracking concept and its examples like 8 queen's
Problem, Hamitonian cycle, Graph colgningprabiem e...(37t 187
Introduction to branch and bound method, examples ot
branch and bound methodlike traveling salesman problem ~
eens : rll 7101)
Meaning of tower bound theory and lis use in solving,
algebraic problem, Introduction to parallel algorithms...(180to 184]
unir-v
Binary search trees, height balanced troes, 2-3 trees,
Batreos.—
nnn ere 86102
Basic search and traversal techniques for trove and
graphs (Inorder, preorder, postorder DFS, BFS), NP-
COMPLE NSS enn ~ 2241028]
nS 1064
‘ALGORITHMS,
DESIGNING ALGORITHMS, ANALYZING
© AtcoRtrins ANN
QI. Define an algortim,
Ans, Any well-defined computational procedure ta ake some valo,or
seu ales, sit snd produces some vale, ost of valu, te eget
‘Sealed an algorithm,
80, in ofher words, we can sy that
shat ransom input into the output i ke
02 Isthereany difference among:
Sequence of computational steps
wn aan algoritim.
algorithm, pseudocode and program?
Epa (RGR, June 2017)
onli Difference among algorithm, preudocode and program ae as
flows
©) Analgorihm is well defined sequenced coletion of ite st of
Instustions for solving a pater problems
Pscudocodes an approach of writing alsritiminthe programing endl
tags (exactly in programming lnguoge is not neces).
‘A rogram is sequenced collection of iastruston writen in «particular
sage (called programming language like, C+, Java ete) which
‘mands computer 1 perform speci asaske
‘esa ll Bseuocode or program can be called algorithm but vce
Aang
(i) Program canbe called as prewdocods bt vice-versa not tr.
in sequen’ Aleoritims are writen only is sequence, pcudocode at writen
fetence and by using some predefined keywords bu program ae writen
eoectUse®: using some predefined keywords end a i fll sme les
Sem by grammar of programming language
soc) *leeith can be thought of a rough ids of any produc,
Preudocode
' blueprint ofthat produ and program the fal produ.4 honest Aro Som)
(22 Dis bporn characters fe gor,
dn alot «Ea tof natns St, towed
access iat Bron, wehave ome se orca
SET elowed bya he algeins
“0m Analg sl ke 250 of me gun o
io tee ea ped
i). Oat Anal hu pod est ono
(i Deftones -Eachand vy nsrsion tenet a
teresa a menbiponn
(ir) Finiteness ~ An algorithm must be such that if we trace out itt
ints, en ral case grim erate ater ie on
ore
(0 genes —tn sit ey itt us bee
vases etn cd ou nay epee go's pad
‘Speer astenugh atch operon dtr aie es
miiretese
or cranple usin, we a about iri son ol
a
(@)fn0, then l= 1
(if a> 0, thennt = ng 0
Ie we wet algoitm for finding factorial of ay number thea it wl
{allow all the above specified eri in following manner
@ Inpat Acuber 0 whose factorial isto be lune.
() Oupue— A ruber, ie ator oPwumber
(dup Deftteness ~ Each isttion is definite the function
be done is to just mulply the number a with oe Fess than that of
a Iemeans—
pla).
(40) Fineness Aigoritr wil trminat when 7 will become 220)
ot
(©) ifetiveness— Each inseuton, (0 1)is very basic a
‘an be done using peel and par er
04. How can the algorithms be designed ?
‘Ans. The tem designing algorithm means creating an lpi ths
sccomplishes particular ask. Creating an algorithm isan at which a
ever be ily aerated
Ont 5
‘There are many ways to design algorithms. We have many design
reciniqus that have proven ote uel in that they hae often ied seo
{Sfonthms These design stregies make it eay fo davise new and tte
‘cits For example, some of esignspprotchesarc"Divide-md Cone’,
‘Dynamic Programming”, et.
“Keommon approach 1 solving. problem sto partion the problem into
caller pars, find solutions forthe parts, andthe combine the sohiton fot
‘fear ino a solution forthe whole
(QS. Whar do you mean by performance analysis of on algorithm ?
explain (RGR, Dec. 2014
Ans. The efiieny of an algortum can be decided by messing the
peformance ofan algorithm. The performance ofan algorithm can be
Ineasued by computing two fictrs ~
(i) Amount of time required by an algorithm to execu (ime
compet)
{@)Armountof storage requited by an algsthn (space comple).
(06. Explain the various criteria used for naling algorithm.
(ARV, May 2015)
o
What criteria are used during the analysis ofthe algoriom ?
(GRY, Dec. 2017)
Ans. Ther are many cfitra wpa which we ca judge algo, as by
+ inigingfoowing things
(0) Des it do what we want todo?
(i) Does i work comeety according to the iia specifentons
ors?
ip 8 ere documentation that detrbes how to use and how it
works ?
tng YA BOs create in sch way ht hy pct og
(the code readable?
‘The above criteria reall vitlyimpontan when i comes to writing
‘tar mot pei for lrg ayes -
above criteria fr judging algorithms are important, but wo most
impetus above cre fo judg lg
© ‘Space complenty (ji) Time complexity.
07, Define algritm, Discuss howto analyse algoritons
es (GRY, Jane 2016)
Ams Algorithm — Refer to Q.1.6: pra Desi At (9, Sm)
“Aaayzing a lpr reas analy fan slain, Ati omar
ostinato nscpriciyeccctathesnaarsed __fostune a imetinan seit wn ona wt he
‘When a lei exec, cies some ofthe esos ng ey neve de, Sina nsahinga at parce
ss amt canal rong ni (CPU) prom operate eof alan. hing ie oot i wi fn ear
immer nh meds nd una Yo old the prog and ag] wets nirmaion oot pristine das Ana ise oaeng
conmaniitnn nih, of lop gle, bot most ens compen) #44 Homaton may be Foes
Stone on alg eu ht we wan ome (iy Averages ~ heaven ring tine of git,
‘is sot easy fo measure, Sometimes get mata sila Han vet tou on eign 0 pat
requted mesure ie Mahenssltot rudy ctade s Roughly 8 ofa a bal a he worsens
‘combinatorics lena probabil theory algebaiedestery,andte abi For example if we randomly choose» nurs and apply ineton-
10 identify the mos signiienat ems in fom. sort, we have fo calculate average time to determine where sebony
Because he behaviour ofan algorithm may be diffrent foreach posi Alk=w-~--1 ~ Ip 4inser element Af]? tn an averee-cat, half of the
input, we need a means for summarizing tat behavior in simple, eh cements im Ali---ei 1) are leas thn Af) and hal the lens ae
understood formula (pewter In sch @ case We hve wo check only hall of he elemens of he
Dating the analysis ofan algorithm our one immediate goal ito dg SOY ALL ad TSO
‘means ofexpesin that issipeto waite and manipulate, shows the mporta nia,
‘haraceatisof enalgorhm'srercorerequirenents, and suppresstedind Gently, average case ranning time ts out tobe aqua fincton
‘eae of be inpu sig, Le, similar to a worsteae nang time
or example the ime taken by the Insron-srt procedure depends
‘heinput. Arson bndres of umber takes loner thensoring ive nam
Ssconly, inserton-sorcan tak diferent amounts of inet sr toi
sequences ofthe sme size depending on how nes sr they lta
(iy esecase~ The bese ening ine ofan grin 2
Jower bound on the running time for any input. mn
Tne besecase we have fo do minum aunbe of comparisons
‘cverticaiah went te mteamenemrimylg mean
Wes ear eae a FO ee at ‘led al array Aft 4i~ |] is sorted in increasing order and element Ai] is
ee Se at a nae meter
soot et Ry rps i a yan
{o predict whether the software wll eet any elceney const that ex
nal analysis ofan algorithm deserts how walla alprithm ee
in the Hestease, nthe worstcase and i averages
(8. How sa alors analsed ? What do you standby
averages and worstcase ofan abortus? (RGRY, Dec. 2011, Jane 201
Ans. Algorithm Analysed = Rofto Q7.
Daring the analysis of an algorithm we check the algorithm frie
‘itferen inputs, Depending on the Ge taken by a algorithm to ex
iret ipat, worstease,averagecate, and best case ate messed
‘umber of comparisons in above case, ai bee,
23. Esplin how time complesity of en ego can be oleate
Give suiabie example. (GPK, Dec. 2012)
or
How sine complet ofan algorithm ix calntted ? Explain with
stb example, (GRY, Dec. 2013)
recat Tite complet of an algorithm ste amount of compute tet
‘25a oan to completion, The ime TP) aken by a program P isthe sum of
‘somite and run ime. Als, 2 program copie one can be exceed
ny mes without recompiling.
The compile ine doesnot depend onthe instance charts.
urn time is denoted by estan characteris). We sul once
in comparing ,
@ Worstense~ The worst-ase runing tne of an gsi s
‘upper bound onthe running tine for any input. Knowing ives us gt
that healgorithm will never take an/longer We need not ake some eh
pv about the runing time and hope tat never gee mueh Were.«8 Anoyas& Desig of Algorth (BE, 1V-Sem)
For calulatng the run time of program we have to calculate
‘akea in sition, matiplcation, subtraction, division, comparison, load scr)
santa on So, we cool aban an expression for f(a) as follows ~
{jad CADE) + C,SUB(a)* C,MOLAM) + CyDIVEa)
Hore, 2 denotes the instance charctersic and C,, Cy Cy C de
‘ime needed fora adn, multiplication, subtraction, ind vision.
‘Determining the number of addition, multipication, subtraction
ion 2 oe have another way ofnd time complexity. We count the
‘umber of operations, We ean count the numberof progam steps fo fi
eution tine which iseasier than hat of erie one. The number of steps
ny program depends on the kind of statement,
Different statements have different counts
Forexample,
(0) Comments count
ero eps
(Assignment statements are counted stone, as they do ot
ny ote loot.
Gi) For iterative statements such as for, while, and repeat
sfaements we count the steps eny for contol pat.
For example,
Tori =
to do
hile () do
(a) In cave of while statement, expression has ie]
count hat is coun for sp.
(©) In case of for loop, we have count eqal to Sum of
counter for and
‘Reninng excoution forte for sslement havesep count of fan
"namin cep ea
increases asthe number of inputs increases In thi e88, the mune of
willbe compued asa function of the numberof inputs alone.
‘When we want to know how the computing ime increases as
‘magnitude of ane ofthe input increases then we have to fad the number
‘eps asthe Fueton oft magne ofthis put aoe.
So, in above way, step counting wll elp a in finding ime compl
010. Wha are te Factors which affect the running tne of an gris) rate
(RGPY, Dec. 20)
Ans. Many fctors affects the runing time of an algorithm or prose]
Some of them ae listed below
a Pan As cade progam renin micore mH
ap CPU Unizaion1C.CBU isalexdy ized by somecrber processes
thea raring ime of algorithm wil intense,
{V0 Bound ~ Sometimes VO bounds ke disk readwite
aio speed
et the ening ime
(io) Overhead Due to many Functon Call ~ There could be huge
sveckcsdon runing function cllismademuliplesines or smal inction
0) Recursion ~Recursif can ease otof overhead which neesses
the runing time ofan algorithm,
(0 Disk Layout ~ For mip disk, RAID might work beso faster
than NAS, SAN of other storage layout
(ot) Contention =1€ tere are multiple threads, they ae synchronized
to scons common resources, then there can be contention forthe resources
tnhich causes thread t wait
(6) Bhieey Synchronization IC tera deadlocks, te agi oe
progtin wil top working or the two thes involved in deadlock wl stop.
‘hsinteasesranning ene of any algorithm.
0.1 Ho recursive goin ar anal ? Anal the exciton ine
af rcv agorith for tower of Hana; problem. (GRY, Dec. 201)
cds. The steps tbe followed while analyzing tsursive lg areas
sows
(Decide the input sis based on parameter
(dent slapd’ baie operons.
8) Check how many times the bare operations is executed.
‘There ermine te execution of basi operation depends upon th input
Se Bd wor avrge ad et es fr pt of em th se
ation depends upon worst cae, average cae nd est ese then hat as
10 be aalyood separately. ae
() Set up the rcurence sation with ome ntl coditon and
sspesing the basi operation.
tga, SoH the recurence o sas determine the rer of oth
lc solving the recurrence we wll she forward and backward substion
Imthod. And then correctness of formula can bo proved with the belp of
nate induction method.
tins TOMETY OF anol — There ae thee pees namely X,Y and The five
Of ieentdamters ae placed on peg X. The arangeent of he
ts tha very salle i pacedon he rps disk, he pole,
of Hann sates that move te dss om peg oper Hing pes Y
oft40: Anais & Basin of Agatti (BE, IVSem)
‘sonar. The conditions are —
(i). Only the top disk on any peg may be moved to any othe pe
(GA larg size disk shoud never be place on smaller one.
Algorithm 14 Tower of Hanel
Alport TOH(, X,¥,2)
{
ite
fi
wite"The pes moved from X 16 2")
)
che
t
TOH(n~1,X,¥, 2}: limove top n~ 1 dks bom X to ¥ using
‘TOHIa~1,¥.2, X): move remaining ik from ¥ to Z wing
)
fone disk hs tobe moved
Dy then
)
“The tower of Hanoi has 2 ine complet
0G" = 1) 00.
(0.12, trite an algorithm for calelation th fu Fbonace! number
8 (og n) tine (GPW, Sime 2012)
Ans, Te leith to compute the fa Flonsel umber flows
Algorithn 1.2 Fibonacci Number
Alport Fibonses (I)
¢
(et) then
wit (fs,
ee
¢
fat =1;
f2=0,
fori = 3 ton
i
f= fat +
2 = fal
fal =
‘eit (Ey
}
)
| oatral mumbers = (0, 1 2,
‘ASYMPTOTIC NOTATIONS
(218 Wha do you ndesund iy te om emps 2
Whats the sgniffance of asymptote notations ?(R.GRY, Dee 2017)
Ans. The wor asymploties means the study of fnctions of parameter
a avtecomes lager and lager witout bound, Asymptotic eens of
Tm x concemed When the input sis are age enough to make ely
aero arom of the running ine relevent. That is, we are concerned
(tow the running ne ofan algorithm inceases wih the sn of the apt
Jeike tm asthe 20 of the inptnereases witht bound. Foal very sll
taps lgrthy thats asymptrcally more efficient wl be the Bes coe.
“Ihe notations we use to describe the asymptotic running ine of an
lao ace defined i terms of functions whose darins are he st Of
3},
Such notations are convenient for desebing the worst-case runing-
time froin Ti), which usually defines ony an integer input sizes,
‘Ween ase asymptotic notation in varity of way For example, the
naion is easily extended fo the domain of real numbers or aeravely,
rested ow subset of the natal numbers
1.14 What lth use of asymptotic notations? (RGR, June 2015)
Ans. Asympote notations ae used o desert he Hinting betavoar of
funtion when the argument tend toward «patel vale, ual in
"erms of simpler funetions, Gener, we use asymptotic noiation 388
cocvenient way to examine what can happen ina anton inte worse of
'n the test case. Various asymptotic notations ae most used fo cloning
the performance or runing dine ofan algorithm
215. Whats espe notations ? Explain each (GRY, Jane 2011)
‘Or
Describe about various apex of expe notation sed algrithn
nats. aa (GRY, Des. 201)
or
Whats nce of a notations? Esplin by
hing epee AN Len TY ee 213)
or
"hat are te different asymptotic notations wed ? Expin
” (RG Jane 2016, Dec. 2010)
or
What isan asympute notations ? Give the eifferet noon 30
fads. (GRY, May 201)
*Prexent che complexity of algorithms.12. Ansys & Design of Apart (BE, 1V 4
(0) bo 6-O@)u6n465 fora
{© 20m 50 a 2008 20
(8 iw fas tl teria
(© tore 10-6 OG) 1D? 1000-6. 101}
forts 108
(0) 67249802) 4569 20+ 8 <7 2 fr BA,
(@) 30237 O(0) adn 3 <0 brn 2
Gh) Lom + tn 2 Oe as et 24.2 Tt orn > 2
() 3ns2O)as3n+ 20 mle an Sbegul OC fred
contin Ca all n>
(On +2000,
Note Wo we te) = Of, rem hing sto
eens sul) an stp per bone) 3h
‘Sort tghtan er bnd e
Foal ales fo lh on, val of finton io}
rtebor
Tehigohaosoah diietmening dentin co die asst
itl Sone often ante sadetows.
(oO) none cent comps tin,
(8 0) tine conpeng tine
(©) Onde ude opting
(@) O(@°)— Indicates a cubic computing time,"
(©) 0()—ndcas especie.
(0 Oto) nds optim computn tie
7) Ke) = Om
Fig. 11 Inuition Behind O-Notatio
nes
Unt 13
(i Omega (0) Notion — Te faston lo) = 0) (ead ws
ctotnistmeg 40 Se ne ote esa ml ea
0) 2 C0, fall n>
just 5 O-noision provides an aot wpe bode atm
von pve an mpone oer Bond
Tors fnaton swe ent yO) he tf cons
vo) Ue): ter ee poe
const any 20h tO Ca)
Searels nd
- ‘For example, the function 3n + 2
son 2 fag) ota + 6 100 fr —
121. 10n? +4 + 2 = O(n?) as 10n? + 4n s-oNe
S Pain eens Fe 12
Te liuton betind © otto shown in 12
Forays ofnto the ight ofa, te alec) estoe 8
(ip Theta) Nonaan Te fae of £6) = 0 (6) ad 8
“torn sthea of gore) lace ess pov coms Cy Cy td
‘such that Cyg(n) < f(n) < Cye(n).
Anton belongs oth fa) the ext poste contants
and ssh hat canbe nice betwen Cg) nd Gg
ites ape
soggy Mithoush OCein)) is
40) Out)
sels 13 ales inv plow of
function fn) and g(n), where f(n)
=e.
Peralta of tte sight omg
the vale of f(a) lies ator above C60)
amor van Cyg0)
In words, for all n 2 Mg, the
fctn 9 cal ee) eins
ctr
set, we write
‘onsant
We sya, go) i an asymptotically ight bound fr)14 Analysis &Dasin of Agortim (@E, 1V-Sem)
‘The funtion a +2 ~O(a) as 3n-+2> 3 foralln2 24nd 39 +2
forall 22,0 C,=3, C4, and my = 2
3 £3 = O(n), 102-4 n+
62 20 ~ (29, and
10 logn +4 = O(log)
theta notation is more precise than bot the igo and omega notat
‘The fnction fn) = (0) iff en) s both an upper and lower Bound of
(16, Give the definition of Big “oh” with example,
GRY, June 2016)
Ans Refer 10 QS (9),
17, Define 2 norton.
Ans Refer 10 Q.15 (i)
0.18. What are the differences between bith (0), omega (4) and
‘them (notations? (RGR, June 2017)
Ans, Refer t0 QL.
0.19, Why do we use asymptote notations inthe snd of lgorthns
rely describe the commonly wed asymploc notation. (RGN, Dee 2018)
Ans Refer t0Q.14 and QU.
Q.20. Briefly describe the asympuotic notations nied inthe study of
‘atgorthms Also write the relational properties ofthe asymptote nai
(GPK, Non. 2018)
(GRY, June 2015}
Ans. Refer to O15.
‘The relational properties of rea numbers ppl to apt ebm
‘Suppose that a) and (a) are asymptially postive.
‘Transiiiy —
a) = ©fg(m) and a) = OCH) imply Ro) =A),
§) = Ota) aod ata) = OC) imply a) - Orh(n),
a) = 2¢0) and gin) = AH) mply ia) = CH),
£8) = ofa) anata) = of) imply fo) = ohn),
a) ~ ofa) and aa) ~ a0) imply fa) = ob).
Reftexvity —
4) = ec),
4) = ffm,
fa) = ae).
. ‘n) = (g(a) if and only if gin) = @cAiny.
eet
Tyce tty =x,
ee aa ae
pec a
or a ee
eT a
ae
in) = a2 b,
fa) “feta = 2 =
fa) = o(0)) “.
(0.21, Define ale “oh"t “0” notation.
ns Tv asyptotic upper bound provided by ometation may or may
‘ot bomympioticlly tight. The bound 2a = o(e?) is asypttcaly tat, but
{he ound 2n = ol) is not
ews notion to denote th upper bound that isnot esmptaialyh,
‘We mally dene oe) (itk-oh of ga) the st
‘{a() = ff): for any positive constant C> 0 there exis constant
> Och that 0 Ha) = gta) fr all> mh
Forexample, 2n= of) bt 2 oh
Tis fnetion —Ka)= of tt
un f
2 Seu
Example —The fnction 3a 2 = of)
Since tin, 2832
ane 2-ctnboe0
3a +2 a(n og og
62 aa
este msn nana sini Ti
is tat nfo) Cg bon! OR) = Cu) os sme
>t Sa and) Can ontse doable 8 Dope et BE, San)
‘Cation esta, fc Snca Kc) Scone! ini
same) ccs nay
tm 0g
Set
(02% Deine ee omer “0 aon
fins by nos eontonisioS-otationas-ctatn 0a
weet Sober tte toad tar oer ag
hate mariag
ean il ny fe) eta.
Formally, We define wt) (itl-omep of gf”) a eat
(= (0): for any postive costat > 0, te
xin count ot vc 0 Call nM)
Forexample, =0(0), but L#0(0")
ais,
‘Thereation f(a) ofa) implies that
im £00) ithe imi exit,
‘Thats becomes acini lage relative tg) asm approaches iy
(023. Write in brief about the significance ofthe following notations)
D0" (yO ii)" h) 0" () ‘@
(R.GPY, Dec. 2013)
Ans, Refer 19.15, Q21 and Q22.
(0.24. Explain te variation ofthe rate of growth of common comptng|
Junctions.
Ans. Tan complet of an algorithm is generally ome fneton oft
lastance characteris. This function is very important in determing how
the tine eguirements vary a8 the instance characteristics change. Als, the
complexity function can be used to compare two algorithms P and Q tha
perform the sime tsk: Now suppose tha algorithm P has complexity (0)
‘nd algo Q as complesity O(a. Here we can assert thet algorithm Ps
fie than algorithm Q for suficienty Ineo. To coafim the validity ofthis
assertion, obser that the computing tie of Pi bounded from above by ef
for some constant cand for allm 2 my whereas that of @ is bounded from
below by defor some constant dand all n,m 2p Aa en