You are on page 1of 126
PUBLISHED BY: ——Apram Singh Quantum Publications? (Unit of Quantum Page Pvt. Lud) Pot No. 89/27, Site=4, Industral Area, Sahibabad, Ghaziabad201 010, Ennai: pagequantum@gmai.com | Website: wwvequantumpagecoin Dethi Office: 1/6580, Bat Rebtas Nagar, habdara, Delhi-110032 © Au Reims Reeve Ns prt of thi pasion my b mpl or tonite ‘nan fr by any means, witht permis Infomation contained in dis works derived rom vores Ieeved io bere Every fot as ben made tense accuracy, however rite the publisher nr the athors _guaranioe the accuracy completes of ny infrmation ublset herein. and neither the pulser nor the sthors sal be responsible for any ees, sions of damages sing ou of we ofthis information, Design and Analysis of Algorithm (CS/IT : Sem-5) 1 Baiion : 2010.17 2 Baition : 2011.12 3 Béition : 2072-13 4 Edition : 2010-14 5 Bdition : 202615 6 Baition : 2015-16 1 Baition 2016.17 8 Rditin : 2017-18 ‘9 Edition : 2018-19 (Thoroughly Revised Edition) 10 Edition : 2019.20 Price: Rs.120/- only Printed af Mayank Enters, DEI TIO03, —_—<==CONTENS UNIT: : INTRODUCTION (0-18 t01-398) “Agaritime, Aralyzing Algorts, Complexity of Algorithms {Grow of uncon, PeomanceMsurerents Stig Sod Ors Sse» Se Sort Ques So. Marge ot Heap Set Comparcon tf Sorting Alois, Soring in Lies Tine UUNIE2 : ADVANCED DATA STRUCTURE. 21802465) Relack Tres B Tne, Boil Hess, tenacs Hens Te, Shp Us UNIT : GRAPH ALGORITHMS ($-1Bt03-406) ‘Divide and Conquer with Examples Such as Sorting, Mati ‘lpn, Canter Hull and Searching Greedy Methods with Examples Such a8 Optimal Reliability ‘lication, Knaprack, Minimum Spanning fee = Pins and Kruskal Algorithme, Single Source Shetst Pa "D's {nd Balinan ford Algol UNIT : DYNAMIC PROGRAMMING (1B 104-205) Dynamic Programming with Examples Such a Krapeak. All Par Shore Pain = Wars’ and Rays Algo, Retour ‘lloction Fst, Eachrahing ranch and ound with Example Such a Traveling ‘Siesman Pb, Graph Coloring Quer robin, Hamann (Gjelen and Sumo Sabet, UNITS : SELECTED TOPICS. G1Be530B) ‘Alps Conputatin ast Fourier Tarlo Siing Matting! “Theory of NP{Completeness, Approximation Algoihne sod Randomized Algae ‘SHORT QUESTIONS, (80181059208) ‘SOLVED PAPERS (2015-14702018-19) (sPaBtosP326) Introduction (1-28 to 1-148) A. Concept Outline Part eee 1B 2B. Long and Medium Answer Type Question ae Part. - (1-148 to 1-398) er A. Concept Outline: Pirt-2 5B B. Long and Medium Answer Type Questions LAR (CSTT-Sem-) | Titroduetion Analyzing. iets Cons A | rte Ors er Pato Berance eran GONGEPT OUTLINE : PART-1 * Algorithm: An algorithm isa sequence of computational sens ‘ht transfor theinput into the oxtpa Input» [Algor] -+ Output + Complexity of algorithm defined by two terme “1 Mie complexity Spacecoupleity + Analysis ofalgorithm The analysis ofan algorithm provides oe bsi nformation about that alrite ike time, pace, What do you mean by algorithm ? Write the ‘characteristic of algorithm, 1. Analgoitumis art ofrlsforearying oatesculatin ether by hand troamachize, 2. Itisa faite dtepbyp-atep procedure to achieve required reel 8, Ttisa sequence ofcomputational steps that traformte ap into the output 44 Analgoithm ia soquesce of operations performed on data that haveto teonpaszedin data strecaree (Characteristics of algorithm are: 1L. Input and output: Thee characteristics require that an agorithan redoes one or more outputs andhave sero or more inputs that are ‘xtra supe Design and Analsiof Algorithme LAMLESTESem.5) 2. Detiniteness + Each operation must be perfectly clear and ‘unambiguous Effectiveness: This rosie that ach peration shoul be ffectivo, Leceuthatpcante deny apron pts sooner srount of tie. 4. Termination : This characteristic reqirs that an agri muxe terminate after finite number af portions. Que | What do you mean by analysis or complexity of an algorithm ? Give its types and eases. iawer | Analysidcomplesity ofan algorithm = ‘The cmpeity ofa lithe ea fnetion an) tht gies the upper Tr ofthe suber af operation for reniog Hane) perormed by an Slgorithm when he input elem ‘Types of comple 1 Space complesity The pce complexity ofan lori athe amount faeungy Reeds torunte compen, 2 Time complesity:Tetine complex ofan algorithms the aout tft nesta an competion cast complesty 1 Worst case compleiy The runing ine or ny rn pt ‘lbs iower than the upper bound except puny osm vals of {betepa where the masimm raced 2 Average case complesty The running tne for ay given wilbethe average nub a operas ovr al blo frtancs Graginen sie 7 bas 4 Best ate compleity ‘Tees cae cmpesityofthe algorithm a fh tn died by the minima nomi o ep ake no ‘ueTS] What do you understand by asymptotic notations ? Describe important types of asymptotic notations. (mre aos Tears — Aotrodetion 2 veto tht ay win Poet 2 these arent fered axa’ and wor! cm More tain compet ction. Notations wed for analysing complexity are 1 ootation Same or oN pus nmatin bunds a neta within constant fcors et! thee eit postive emma a4 Me iva ot he vale a fo sap bees Sie and etal (css 0m.) rion 0d sta) a) eso) fa) 9g) ig. 13.1, 2 ONotation (Upper bound): 4a Blgeh is formal method of expressing the upper bound of an goth’ raning time 1 Its the measure ofthe longest ameunt f tine it could possibly take forthe aigrita to complete Mor ormaly, for non-negative functions, fn) and gin if there fist am integer anda constant e > O such that frallintegers Fin) sata) Thon, inbig-oh ofan). Thais denoted as: Tea) © Oe) in, the set functions which, an gets are, row faster than aconstant tine ee xin) a) a= Oa pig 132.) eo Design and Analysis of Algorithms L-ED(CSIT-Sem.5) & Notation (Lower bound + ‘This notation gives lower bound or afunetion within constany factor. 1 Wevwrite fn) = génpifthere are positive constant naecrach {atiotherighten,thevalve afm alwayslieson or shove cx) te) stn) °° fia) = 04) (riers) 4 Littleoh notation (o):It is used to denote an upper bound that is ‘ssrmplotiealy tight because upper bound provided by O-notation is ot tight. ‘o(gn) « fn) for any positive constant c>0,ifaconstantn,> Osich that O. 0, ifa constant n,>Osuch that Os eg) < fin) ¥ n>) BTA] tr7m) «100° 2+ nb 6m then show that fn) = O12". == fin) 10082 + nF Foran 100° 2 obs 100" 2 nbs nF 2100" 24 2 For tant 100°2° snes 100" 24 29" 103° t ‘Thus, fn) 808) REST |oonsider the following function: inv Sequentiaearct Ant ints) inti {or (int {0,1 Lare constants = the numberof eb-problems inthe recursion {Ub the portion ofthe eral problem represented by each ‘Then Tn) can be bounded anymptotclly allows cant howe feycormenerda sett same: rayer($) soe he given formula the variables gt the following valves 14 * 8,62, fn) = 10000, log = og? = 3 ane caneet {id= O1n4*°8) = On) fo) = O40!) = O78 Sine tis equation holds, th fire cave ofthe mater’ therem applisto the liven recurrence relation thus esting elation a Tn) = (a's) =) Fork =1,wogst Cave tie trve that fin) = 010m) ells that: Tin) = 00%) 7 ogi) w= 272) rw-21(2) on nthe ve formula the varies ge the allowing ves 2,622, fn) log log. Beart Introetion TSR (CSIT Sem) fin) = Ons) =n) a Since tis equation bold the second case ofthe Master's theonem app eS ea rturrence relation, thar resulting solutions Tn) = tr lgin) = Ota og) ae is trthat 7 fry «tas for > 0 ditt ated ata (8) se foroe< andl uit aren lows that. : Tn) = 4h) a roar(‘)ex re rm evr ning te: coe be 2 fin)= 0, loge =log,2= 1 earns ikoets fin) = tn!) = 260) Siace the equation hold, third ate of Master's theorems applied. Now, we hate to check for the secoad edition of third ease, iit serve that Por B=1woget a(S) sero Foes ace 1) cars dorset we choot = 2, iis tr that 2 Lede ms bat ynzd 2 0,8 flows that Tn) = 94%) we insert once more the neceseary vais, weg ‘Ta ¢ O(n?) ‘Thos, the given reeurence relation Tx was in (2) Ty] Tue recurrence Tin) = 7Tin/) +n? deseribe the running {ime of an algorithm 4. A competing algorithm A has a running time 7(n)=aP (nid) +n. What is thelargest integer value for mA’ is saymptotcally faster than A? aa(S)ent 7) Tos ar (2}en 1173) rs eguton (114d resign fr goth A and equating (22) efines the unin ine for lit A Then orig value of fecwheh acyl ster than Awe ad eoymptticotatien ‘Gereeareaceby ung Masters metin. Nor, compare equation 1.73) by MH) at (2) +n) we get, ant é fo ‘Naw, apply cazes of Masters, theorem as Cased: fin) = O1aw4) = fn) = 0028-4) = fn) =O(n280-08 > fin) = 0002) Hence, case of Master's theorem is saci. ‘Ts, Ta) = 8(n'™*) = Tn) = 0052") Sine recurrence given by equation (17. is asymptotically bounded by ‘ootation by which is used to show optimum tine we have to show that recurrence given ly equation (172 is bounded by f-notation which shows ‘minimum tins het at) Forthe use etsy the ease 3 of Matter theorem, et a= 18 rine ser (2) 0 ‘Therefore, this ehows tht Ais axymptoticaly faster than A when TEER sete te ttwingrvurence: 1-100 (CST Sem-6) Introduction stomcesttsems) tat Tin)= Tn) + 00g) Ta) Og =) asp asa pteaoo i Ingmton A west rney= 72%) sone) was) 0m) = 72") 184) Putting the valve of =m) in equation (18.3) 085) where. ERT wnt co you meant reurvon? Esplin your answer ‘than example eae 1 Reewsinas roe erecta as topo Sepersn 2 niet recroe cnr when on ncn letra ‘ecasth et ncton 2 Sipe in pear ctaig ser aumento ior tcalatemet oa secnd recede tot nay cesta rerang Silsatnent ct te ogi pode 2 4 ThenPieaedrecurve pred She propane ‘torun indefinitely. * 8 Acre rosea hat have th lonng ro proper: Thee most be errr cll nn eri ch Be ror dct Bach tine the cea mt Be dete ct & Areca paced with hse to proper tb we defined. : 7. Silay ution i sid ob recurve defied ifthe fein ‘definition refers to itself, = Design and Analysis of Algorithms LAIBICSITSem.5, For example: "The factorial fnetion may aso be defined as fellows a Ifn=0,thenn!=1 ‘Here, the value of! expt given when m = O(tbu8 Of th ‘base Fala. b In>0,thennlen. (nD! Her, thevalueot lor arbitrary isdefined in terms of small ‘alo fm whichis daser to the base value ‘Observe that thisdefiition ofa! is recarsive,snceitrefersto itself when, wes (r= ‘QaeTAD | What recursion tee PDeseribe, mer 1 Recursion tree is a pictorial representation of an iteration meta srichisinthe form ofa tree, whereateachlevel nodes are expanded 2. insrecursio tre cach ode represents the cst ofasingle wubprobem, 18 Recursion tres are particularly useful when the recurrence describes {herunning ine of evide and conquer algorith, 4 Arecursion re is but sod to generate a good gues, whichis thon ‘ered the ubsiuon method 15 tfeamethadto nae the complet ofan algorithm by iagramming fhe recursive feneson calle ‘Thiemetbod can be reliable ‘GaETAE Sotve the recurrence Tin)=Tin-1)+Tin-2) +1, when T0)=0and Tt in D4TH—2) +1 ‘At Bevel, TU) willbe ual to 1 when, ben-d Pete ate at =Pedege ot Introduction 1-12 (CSITSem-6) Fi i tcl i mea eet a NS Let IN, we ne ab DY mee nb DY 0 ah DY eset Te-W —* » [eset nm “2 2 ‘GasTa] soe the following recurrences Tin) = Tin) + Tl) + Tl) 2m 21 ieee] ( 5) Cie) Se). (is) (se) (a) JINN i NANI TINANAN Tin) « ne 8 Ee. rag og times Tin) =ST (nf) +n, and Tin) = SP (old) + n? where cis constant and n is the number of inputs. Find the symptatic bounds. [ARTOUIS:14, Marie 0 Design and Analysis of Algorithms nee] 1-131 (CSATSem.5) ‘m= sr(3) sen sve can draw recursion tree fo €2 1 logy times Tn) =n4ntnes Tin) = tog”) 3 eer : 3 s INNIS NIN Ta) «nomen on bg ties 1) = tog 10) = 5t(2) ont aaa Feng eatin Tovar (8) +160. ] [Now apply cases of Master's theorem as Paneth cenly sone) wa whe B= dat feo cor tetuntnh tite Tarai EEEIEG] 01m tn tong by tre med Taeostun onan EEE _ Introetion [14 (CHIT-Sem-5) | sung ed Order Stine Bhal Ser, Quick Sort ‘Merge Sort, Heap Sart, Comparison of Sorting } “/ Mgorithns, Sorting in Linear Time. Et PART-2 CONCEPT OUT! ‘+ Shell Sort: Tt is an algorithm that roughly sort the data frst. ‘and move large elements towards ane end and smaller ones {ewards the ot Compesity: Otn) ‘+ Heap Sort : The heap isan aray that can be viwod as 8 outlets nary teh reeled onal eesexcept the Complexity: O(log) + Merge Sort: I works on divide and eanguer approach firs, Aides itis ois and sori and the ote how sorted one ist. Complexity: Olen) + Quick Sort: Te works on the principle of vide and conquer Tt works by partitioning agven array. Complesty 00) Questions Answers _Long Answer Type and Medium Answer Type Questions —eE—xEEEeE \ Design and Analysis o Algorithms 1-16 B (CST So ‘QueTAB.] Explain shett sort with example. | “Anower 1. Shel sort isa highly efficient sorting lorithm and ibaedoninserton sort algorithm and wecan code it ens. | 2 Teroughycorts the data fist, moving large elements towards one eng | sd small clement towards the ober. 4. msl sort several passes over the dta ie performed, eth incr than | hela. ‘After the inl pas, the data fly sorted ‘5 The-lleort doesnot sort the data itself increases the efiienyo¢ other sorting algorithms. he Be etait ee tara a FE emicr-niria aed a a | “EERE PREP piper i ‘The distance between the elements to be compared is 3. The subfiles generated Teeter omer ‘Subfile 2 a] ald) al) all Tee ae EE 3 SEES T cele TeleleTs 2 ‘Output of pas i inp o pass 2and detnce » 2 EE ee Introduction vo] «6 so] 6] v0] vo] 50] 96] v6] oo [os [90 [os o Outptofpasa2isinputto pas and distance» 1 io [os [20] 96] 50] «] #9] 75] 65] 00] 75] 90] 65] © Output ops w [10] 20 [00] 36 | «5 [50] 65] 75] 15] 0] [eo @ Fig Lika) Bie LIE: | Deseribe any one of the following sorting tech: i Selection sort Insertion sort Tarwor 1 Seletion sort (A): ne length Ad forje ttt mallet oj frie js tton EAU 0 and Ai > key bale tel feta Alera ehkey Ju 1ATB(CST Sem 5, Design and Analyse of Aloeths Que IAT] Write non-teterministic algorithe for sorting, aro algorithm that, even for the sae inp ‘iteent rung eraonsand exectne Aaswer [Non-deterministic lgethms am exhitit eiferent Behaviours 0 NSORTU,B): forse ttondo cbse ‘BY =O then fre Bull fender forte 1ton-1d0 iE By <= then fire na print) 10, sass ‘Qaetab | plain the concepts of quick sort method and analyze _——-— aM (CHITSem-) Inteadetion pam ee & daitauisx 6 thende id z 6 thenexchange Al AU 1. exchange Al #1) 4 Ate retuen'+1 Example : This example shows that how "Pivot" and "Quick ort” work Suppose A» 1, 4,156,8,2-6,6,3,5.6,91 Sor the array wing quik sort algorit, Solution; Given aray tobe sorted BEDI T2Te1s1s15 1819 | ‘Steps The arrays Pivted about it it eloment ic. Pivot (P) «9 ele] ]2]° EE a ‘Stop 2: Find fist element larger then Pivot (make underline) and find ‘Sent not larger than pivot fom end make oer line. (RRRUBOTETT Marks 9] ite complexity with suitable examy anwer Quick sort: (ule sort wus by partitioning a given array Alp. nto twa non-xpty secrdiy a indigo hey indie ise than or oq to every key in lg +1. Then the two subareas re sorted recursive ll quick srt Quick Sort yp.) 1 pertien 2 qePanttientA.p.r) 3 Recursive call to Quick Suet (A, ¢-1) 4 Recursive cll to Quik Sort Ag +1.) Asaf step, Quik sort chooses pivot one ofthe items in the array be fered Then ray partied on iter ie ofthe iat. Elemental ares than or equal opiot wilmove var eftand elements that fe sreater than or equal to pvt wil move toward the right. Partition 4,7.) Loreal 2 tep- 3. forjeptor-1 PE EPLEELELELL! P + + ‘Step 3: Swap these clement and sean agin. SLEEPER EL EEE 7 SEEPELPEDEEEEE P tT Vesela Grae serirenine Design and Analysis of Algorithms Thea inthis situation swap Five withering. 1-208 (C8ITSem-8) Introdetion EDEREEEE EET P ‘Now, Pivoting process is complete Step 4: Recursive sort subarray on ech se of Pivot, Subarray 1: [2]7]3]1] Subarray 2: (9[5]6]6]1[5[8]9] First apply Quick sor for subaray 1 BAG PTF line Overine [a ray Uniertie Overie ‘The pointors have croseed, 4, overlie oa eof underlined ‘Swap pivot wthoverline DEPTS) Sorted array Now, for eubarray 2 we apply Quick sort procedure. PREEEEET ? Tr Overine Underline ‘The pointer has crossed. Then swap Piva with overlie, Sobaray 4 i: BABoG P © ovesine ‘Swap overline with Piva Orerline on eof underlined, ‘Swap Pot withoverliz. [Now combine ll the subarrays Sonedaray—ef aL Pe Analysis of complexity: i. Worst ease: 4 Let Tn be the worst case time for quick sort oninput size. Weave Tw) = mss (Ma) + Na—g-1) +0(n) (4383) where ranges fom Oton-—1, sine the patton prude two regions, ‘ach having site n= ‘Now we assume tht Tn) sen for ome constant ‘Sebstitting our assumption in equation (1.18.1 we get Tin) sax, eg +n q= 11+ 010) = BEEP +0411 +088) Since the second derivative of expression ¢+ (nq 1 with respect ‘ogi postve, Therefore, expression achievers taninum over the range 09m 1 a one of the endpints 4. This gies the bind a gua + (9 1 (n= DF 5. Continuing withthe bounding of Tn) we get Tin) ent ~e(2n-1)+ (Son? Stace we can pick the constant clarge enough wo tht the cn —1) erm ominats the) ter. We have Ta) = 0108) ‘Thus, the worst case running time of quick ori (n. ane Lf the split induced of RANDOMIZED _PARTITION puts eonstan, fraction of elements on one side of the partition, then the recurren ‘tree has depth 6 ayn) and work s performed at each evel, ‘2 This isan intuitive argument why the averoge case running time y RANDOMIZED QUICKSORTs i: log) 3. Let Tn) denotes the average tne required to srt an array of, slements, ell to RANDOMIZED. QUICKSORT with 21 clemey, ‘array takes eonstant tne, sowe have M1) = (0). 4. After the eplit RANDOMIZED QUICKSORT calls ite to sor tng subareas 5 Theaveragetime to sort an array AlL.-ghis lq and the average ing tesort an array Algt1. ls nal: Weave Tin) = Un TU) + Tin =D 4S, Ne) Tin=9) +80) 8) ‘We know rom worst-nse analysis ‘MH) = OC) and Nin-1) = Ofn") Tir) = Un(@(D) + O68) + Un, (ra) +Tn-a) +) =n 8, (TQ) +Te—9) #QIm) 118.2) = Vn (2S, T8)} + (0) =4a-'s,,(T1R) +0) (0.183) Solve the above recurrence uring substitution method. Assume that To) ann logn + bforeome constants a> O and b> 0. ean pick 0 and 8 large enough ao tha m log n +8 > TU. Then fer noi we have Ta) 2**0,,,2n(ak log h+ 8) +649) = Bi", log = VBC!) +281 @-D+6n 1184) ‘A his pint we ae claiming that 9, flog V2 log n— U8tn?) ‘Sebttuting histlai in the equation (L184), meget Te) < tal Vt gn nr-1) «01 San logn—en's+ 2+ @n) 85) nthe equation (1.18.5), 62) + aud an/ are pelynomigls and we ean shoose ‘large enough so that on dominates tn) ‘We conclude that QUICKSORTs average running time i fn log) Discuss the best case and worst case complesities of ‘Quick sort algorithm in detail. 1-220 (C8IT-Sem-5) Introduction Taswer Best eae: 1. The best thing that could happenin quick sort would be that each parttoningetage divides the array exoty inh, 2 nother words, the bust to be a mein ofthe keys in Alp] every tine procedure Partin’ eal. ‘8. The procedure Partition’ always splitthe array tobe sorted ito two ualelaed arrays 4 Ihe procedure’ Partin’ produces two region of ie 2, then the recurrence elation Tin) < Mold) + Ti) + tn) s 272 + On) ‘And from ease (2) of master theorem ‘Tin)= ein gn) Worst cate: RoforQ.116, Page IH 17B, Unit ‘QueTRD] Explain the concept of merge sort with example. 1. Merge otis asertng algorithm that ses the ieaof vide and conquer 2, Thisalgrithm divides the aray into two bales, sorts them separately snd thea merges them, 2. Thin procedure is recursive, withthe bse criteria thatthe numberof erent inthe sray fn one tha Algorithon MERGE, SORT(e,p,) Lifer 2 thengelipeniel 8. MERGE-SORT A, 9.9), 4. MERGE-SORT (A, ¢ 17) 5. MERGE A,p.¢.0) 2 mera 8 Croat arrays (Lona Mand RU 4 fein ttom, de Ta =apei-n Design and Analysis of Algorithms 1290 (C817, endfor 5. forj=1t0n, do RUl = Algo endfor 6 Uns t=, Rings tee 1 ietjer 8 fork=ptor & if Lasre then alk) LE feted ee ABR feist endif endfor 2 eit Example: 10,25, 265,35, 4,8 L._Divide into two halves + Gatti 5 wnorns os 8 Consider the second half: 35,48, Seguin divide into two subaraye e.8 8 ‘ 4. Menge thes two ert sb-arraye, L-UB(CHITBem5) Introduction Te BA ‘Thirst sorted array. ‘Ge ] Determine the best case time complexity of merge sort algorithm. Answer 1, The est case of merge srt oceurs when the largest element of one array ic smaller than any element inthe other array. 2. Forthiseate oly? comparisons of aray elements are made, Menge sort comparisons are obtained bythe recurenee equation of ‘herecursive alle wed in mere set 4. Asit divides the areay into half wo the recurrence functions defined i {e+ -na variable ht indicat depth ofthe recursion, we get o=2(3)-2(3) +» 5 By os Tm) =27(2) +n 0219 © Forthetest ease there are only comparisons hence equation (1.212) canbeveriten at Tw) o0(S)ea 1 Attest eve erection tee en he togye 4 Sothorecurrence function is defined as = 207 = Al) thea argest 1 lee gest © ltr sheapsize A) and AUP >A angel then ager er ‘largest =i then exchange Ai] 4 Aflargest] 10, MAX-HEAPIFY 1, largest] HEAPSORTU): 1 BUILD. MAKEAPCAY 2 fori «length A} down to2 & ——doexchange Alt ¢ Ai) eeneanen ‘ Ieap-size (Al hespine tA) —1 5 MAXCHEAPIFY 4,3) BUILD-MAXHEAP (4) 1 hoapesze (A) length AL 2 fori ength Al/2) down a1 do : 1-208 (C8IT-Sem-s) Introdetion 3. MAKHeapifyiA.D) ‘We can build» heap from an unardred array inner tie, ‘The HEAPSORT procedure takes time Oln lg n) since the call to [BUILD_HEAP takes time Of) and esch of the n= calls to MAK Heapty {ales ime Og). ‘WoeTT] sort the following array wring heap sort techniques : (6, 18,2, 25,7, 17, 20,8, 4). Discuas its worst case and average care ‘time complexities. Taner (Given array is :15,18 2,26, 7,17, 20,8, 4) First wecallBuild-Max heap heap size Al = 9 =, 12 to call MAX HRAPIFY (A) 2 tate call MAX HEAPIFY 0) ‘All = 8,4 Uf) =25, Ale =4 A> ain All>ath Now eal MAX HEAPIFY (4,3) AG = 2, 37,0) Ausaul largest ‘Al >A Dargest 2217 largest 7 largert Ali esa flanger ‘AUl>Am) Atal ‘Now all MAX HEAPIFY 2). A) Abr 1 Targest 0 6 largest] Now, Ausatt Ausatn ‘Woall MAX HEAPIFY A, 1) Alleaul acgest= 2 Aiageet] > Ar nd large “Ride A lagen) largest =2, 20/22 Design and Analysis of Algorithms 127B(CSTTSem.5) 1-288 (CSIT-Som-5) Introduction XQ © 060 GEERETT All| A (7 largest #1 pgsin call MAX HEAPEFYUA, 1. get Alle argest Now, All <4 Uh gy largest = 8, A largest] >A [r] gq ® largest i, largest] e+ fi) © OO B sofia tree after Buld MAX HEAPIPY change A [I and AIT ad soe = ste 127-126 Q K BD 2Te[s)e> am © 06 B _Agsin call MAX HEAPIFY(A, 0) we get Now i= 9 down to, exchange A [1] and A [9] and size = size 1 and cll -HEAPIFY A, 1)each tie. exchanging AU} +4 [9] @ = ® exchange A(t] and AI6] and now QO Gobo OO6 f ‘Again all MAX HEAPIFY A, 1) eesiaa ee oS) Q Ome: X YQ ‘xchange A Ian A 6 and ow ze 5-1 LX O@O® @ Sd © GoEEE Now exchange All and AIS] ann sne-1« 8-167 - © * Agia, call MAX HEAPIFY (A, 3) Design and Analysis of Algorthins 1-291 (c4 Q OX © ® exchange A [i] and A i] and sie = fol 3 a ter call MAX HEAPIFY (A, 1) ‘exchange A [1] and A 3, size =3— ® 2T*[s]7[*]*|"] >= Average case and worst ease complexity: L 2 ‘We have seen that the running time of BUILD-HEAP is fn. ‘The heep sot algorithm makes aca to BUILD-HEAP for creating 0 (aman) heap, which wil take O(n) tie and each of the (nell to MAX-HEAPIFY to fix up the new heap (which i created after ‘exchanging the root ad by decreasing the heap sie), ‘We know MAX-HEAPIFY takes ine Otog ‘Thus the total runing time for the hosp set is On log 1-101 CHIT 2 re Wot, sort? Apply heap sort algorithm for sorting 1, 2,3,4,5,0, 1,80, 10. Alan deduce time complexity of heap : ra De ren sc. Leet preteen hen epaanrae ome Se ‘GueiE [Explain HEAP SORT on the array. Illustrate the “operstion HEAPSORT on the array A={6,14, 3,25, 120,76) ARTO BOTT Maks 1 [hawwer Heap ort: Refer Q1.2, Page 1-248, Unit ‘Numerical ‘Originaly the given aay i: [6, 14,3, 25,2, 10,207 61 First we ell il Max heap oo call MAX HEAPIFY (A, fay fiat we call MAX HEAPIFY (4,0) ‘AU)=TA Ld «Al 925,426 Teter sl=8 re right dl =9 859nd7>25 False) Then, largest 4 99nd 6> 25 Fale ‘Ten, largest =4 Alleals ‘Norcal MAX HEAPIEFY (A, 2) B em © © ~ tnd call MAX HEAPIEY = sp [Now ell MAX HEAPIFY (A, we get [Noweschange A (i and A 8 ad ‘Again call MAX HEAPIFY A, Sofinal ree after BUILD-MAX HEAP is ‘Agtin call MAX HEAPIFY (A 1), Design and Analysiof Algorithms LBM COMMS, Again call MAX HEAPIFY 2) exchange [1] and A [5] and now site = 6—1=4 @ @) gg Oo) .~ & o © @ ® @ 2 7 ele]s ‘Again, ell MAX HEAPIFY (4,1) ‘exchange AI] and A (i and ®. © SF @ © © call MAX HEAPIFY 4,1) exchange A [1] and A (3, size «3-152 So oo [ate call MAX HEAPIFY (4,1) exchange A [I] and A [2] and size «2-1-1 GO — zis ‘Thus, orted array: 2T2[e se] 7 [wl ul ls GiETRE] How wit you compare various om.) Pes (CHT Sem) Introdetion Trawer] Tame] Ave | Worst | Babi | Wetiod | —Oiker ner Tamron | 00 [Ou | Yen | trim | reagan aa ae Yes | oatee [nie] Ye | Serie [ewe ep ose) | Omen] No Gea | Obes) [om | Wo Gee TR7] explain the counting sort algorithm. ewer | Counting sorts linear time sorting algorithm wd osort items when thay ‘long toa feed andi st Algorithm Counting Sorta, 8,) 1. let C0.4] be anew array fori 0tok ceo fore 1totengthlal Ae CLAY = CIAL +1 ‘Ci now contain the numberof ments equal oi forte toh doc «cus ch—31 {7 Ol now contain the numberof lesen less than r equa a for lengtlAl down to do BICIAgI AU) 10, AY cali -2 ! Design and Analysis of Algorithms "QUeLRE | Whats the time complexity ofcounting sor? Maser, 1 WCET em) Intenduetion theoperuionotcuntng ser onsen A= 66348 or 7 [aa [eur | meni ey] SS posign and Analysis of Algorithms 217 B(CSATSem.5) a hiciet sp tees + downto 4. fF snl and = key th doggie 5 then retort.) 2 eb 6 feast 4, for = nl ent 1. thenretur NIL 14 dake, = hey 8. ese DISK'READG|) 1. beyfel =H, ‘ 8. retum BTREB-SEARCH (6s, te. laden +2 ‘The number of disk pagee accessed by B-TREE-SEARCH 11, DISK-WRITE(] tun tlagawhrehisthebeightofthe tread isthe nomberss,” 8 DISKAYRITEL] inthe tree Since ws} <2, tinetaken by the wilelopoflines 23 yg,_DISK-WRITEL] cach nodes is OQ) andthe total CPU time i201) = OC¢logn) Coe sed by BTREESPLIT CHILD i The rca perms BTREEINSERT®) axidskeoperatons. 1 reretif [BIREE-INSERT-NONFULLs 5) 2 itnl=%-1 tenis 4. thens « ALLOCATE:NODE () iftette < 4 wales then while 21 and&< key 5 eafld FALSE okay © heya} 6 aleo jet 1 gbler ey, fF & BIREESPLITCHMDS,1,) ie} ened +1 BIREE-NSERT-NONFULLs 4) DISK. WRITE) 10, eee BAREPINSERT:NONFULLr,§) ‘lao wile (21 andh =H roan fae ht Insert Bs + [RIS i aaa 4 iE [aU P Inset Ys Insert seat Gs Fae) GR) n (RE) vee) Ilnimum degree #22, Prove that:h og, **+ se. ie, 34ay mee met rN Lal 1 Toro contin a et ony 2 Aothersoes contain at stay Thor are toast nodes at depth at east 2 odes at depth at east 2°" nodes at depth and 2 nodes at depth. TERRI ts 1, tne tr any may Bae of Dik a 2308 (CSITSem 5) APMED Sing, nzreu-p D2 =) ao (CeBjeat 4 Sofsine nRaseqe 5 Taking log both sides we et Slog (n+ DP —a . [Part2, ‘BinonialHeops Fibonace! Heaps, Tries, Ship List CONCEPT OUTLINE : PART-2 * Binomial heap: Abissmial beapisa data structure sisi) Erte sn upg he operon oe ben | + Operant on nome: Tate aking Ge © Imerton & Reno i Deceating "ibonacl hep They rink nto ep ordered tes ‘is also collection of trees. > + Operations on Fbonacei heap TP inertion Union cS WL Entracion iy, Linking ‘Deletion iv. Decreaing ‘+ Thesis kind ofsearch reused to store dymamicoratsctine sets, + Skips alayeredlinked it dat strcture a" Heap and properties of binomial xe. ‘GRIT What is a binomial heap ? Describe the wn pefine the binomial heap in detail, Write an at + a jen of binomial ire Mr otal numberof node a order kare 2 7 Ferenc (le. Gane dhe ae ee aa ayetetse see rial een B88 eftto right. 4 nial heap. on rithm for ‘operation of two binomial herpes log ier] ‘Biaomial heap : Refer Q. 2.16, Page 2-908, Unit {Union of binomial ea "The BINOMIAL HEAP-UNION procedure repeatedly links bsemial {ress where roots ave the same degre, ‘The following procedure links the B,, eee rooted st node to he 4, ,teorooted etmodes, that, eas: te prea fy. Nodes et tomes the rot ofa ee, BINOMIAL-LINK 4,2) pole2 sibling hale) cls] ey Im. degrecte] « degrets] +1 ‘The BINOMIAL HEAP-UNION proedure has tmophases: The frst phase, performed by thecal f BINOMIAL HEAP. [MERGE, merge the rot lists of binomial bape Hand nt & Single inked list that i sored by degree into montaneally Increasing order. ‘The secnd phase links root of equa egret uni st met one wot remains of each degre, Decnate the hnked lst H sorted by Alegre, we en perform all he Hee operations quickly. ‘BINOMIAL-HEAP-UNION(,,H) 4 He-MAKE-BINOMIALHEAPO) 2 headlit « BINOMIAL-HEAP-MERGDI, 1) — ear 2928 (CSITSem) epneeee 0, REBB ESB REERE Advanced Data sy, Free the objects H and Hut notte its they point ‘headta = NIL then return prev NIL xe healt ext sibling shilenextr# NIL Go if ogres deresinexts} or (singlestx] «NIL and degrelsibing nex] thea prev ened len if este kesb] 9 theneschange 0.9 10 FIB-HEAP-LINKGH,3,3) 1 Ald) NIL w dedel 2 Aldex 14 inf) NIL 15, fori Oto Dini) 16, doit) NIL | 1, then aA to the root ist of | Monet heap eter 290, Page2-408, Un Structure of ibonace heap: 1 Noe ratares 1 Tefen chi a Th mde tet hi sie 1 Me fil dee” tna the umber of hi tape cna nb of en of i ‘Tho structure contains a doubly-linked lst of sibling nodes = i ‘ i L 2 4 pesiqn and Ana ‘GeeBIs]] Discuss fotlowing operations of Fibonace hea L Makeeap ysis of Algorithms heap H 2-43 B (CSIT-Sem-5) wih Nusber of sit { $ @ ‘Fig 3223 ep ea) fi in = NIL or ey (AL < key) sr | puntion for uniting ¢vo Fibonacet heap: FIBHEAP-LINKUL 3.2) ieee 1. ramon thet isto aah 2 tnaley acho, lnerementngdgrets MAKER mark] = FALSE seit GeeRAe| DetneHhonast hep. Discuss the structing y, | n=? Fibonace heap with the help of a diagram. Write a funcie, --UNION, H, ro Fbonace heapas Em” NEKC 8 functigyg, | FIBEEAT ON sree ‘min( ff] — minlH,) CConestanste the rot lst of, withthe root staf 1) or (mil # NIL and mil Advanced Dat 2448 (CSITSem-5) Se ee rithms 4 lefle] ex SS, poses ental of Algorithms 2450 camTSens) © PSE Fin aS ea ee Spots heather Se oe ea an = NL or ky < kein) ea ee a ea 9. then inlA eo gond toys Finer. inne odes that fo sinetnet rc! Mi cin BEANE ie petetenac heap and 2 be te resulting Fibonace een : te amaeetettten Sega ptm . nono ace tthe tesla ith character. ra afte corresponds totes ring wichin conten pe est dhe $ 4 Beier ona path rom the roto this od, FaE| Weitea set to serch avr hyn tae: key in tries: ten Pikaminerastlag Pinto teh 2 eed Ti thn nen | 3 thn hho 2 eeeasai= thou ae dedi ta Bear earths 8 pide hater ies Tens mth at ite! ote Pn 1 een itt hnPathrwe Paley pa © ental ex, Tec hen : is Moca ch oan hee Hating i ht shen tee ew » ean iets nd fh meant 2 rune EGER watts op ta? Wha are properten? [REGRET] what is trin? What are the properties of tries? ‘Aki it bitin ayers ‘Tae bottom lori an ordinary ordered inked it Bachhigher layer acts ax an express Ine’ where an elerent in ayer ‘appears in layer (+ with some fied prebbiity9 (wo cmmonty ‘ued vals frp are and 40. ‘Onaverag, each element appears 1-p (casually a pedal bad element a the front EI 1 Atsi(igal t/a pets fie) kindof serch te! erred ie da urctaretat s ed to sre apm ssseitve array where the Keys are usually ering 2 Unltabinry ere te, no ndeinthe tre store the ey asc vith that od nse TER ntl; ten inthe ee defies te ists, nthe tallest lent thekipiinal toes. —_—_—l —_y 2-460 (CSIT-Sem-5) Advance saan carmen _____“rerestn., 5 Theapli contains, learitim base pgp Properties of sip ists 1. Some clements inaddtion to pointing tothe nex, ‘laments even further down the list | ist element that has kf A 2, Alerel kelement i alist lement brary, | 5 Thott pier ptsitbenertlemetinthe ig pen, | patton lent eninge che, | tothe next vel element Geek] eepnninertion, searching and deletion gy, “st stip ist. mt, | ‘answer Insertion in skip lst 1. Wevillatart rom highest evelinthe list and compare key ofthe carent aoe with the key to be inserted, Of eta 2, hey of next node is less than ey to be . moving forward on the same level 4 fkey of next nodes greater than the key tobe ina the poatertocurrent node at updatel/ and move: continue our search. Atte vel, we will definitely finda position to insert given key Invert, searhikey) | local opdatel MaxLevel] sxe header foci := t+ level downto Odo hile forward +key forward} pda s=x 55-9 forward) i:srandombevel Stl st evel then foci:=lit-stevel +140 do ‘pte = lists header Ase set| stamabeNode, fori: Otolevelde > forward plat forward lemon a, "hay er then we tag, rte then we ‘one level does = Beene rte earch, valu) BEER Sell ew 2478 (CSITSem.5) alist iat x» kay level down to 0 do ore farwarail > key forward ax forward} 2 ey escarchKey then return x - value weil i Jip list: spl esr sect -obeder pl downto 080 wd he forward ree pour ten ole do Megat» frvar#the break a rw ward te) St eel> Ondine rvs el =e Meese: l= ne Bice cee BEE ‘VERY IMPORTANT QUESTIONS ‘questions are very important. These questions iE ‘may be asked in your SESSIONALS as well as UNIVERSITY EXAMINATION. Q.1. Define red-black tree and give its properties. ame Refer Q. 2.1 jertion and deletion operation in ared-blac: Qa. Explain thei tree ‘ax Insertion : Refer Q, 21, Deletion Refer Q: 26. gp (cst sem) Meaney an by BAF of onde Dy, Qa. What do you me um Refer @.28. qt, Baplain the inerton and deletion opergy, Bela operation Refer, 28, ae Taser peration Refer Q.210, (5, What is binomial he heap. asx Refer. 217. 6. Whatis tries? Give the properties of ti, ‘aa. Refer Q 224 = 7. Explain skip list. Explain its operations, ‘aa SkiplistsReferQ. 2.26. ‘Operations Refer Q.2.27. 668 searching operation: - Mh ci 2 Deseribe the uni, ion op Graph Algorithms eS (6-28 to 3-128) “Acconept Outline POMEL wwe 3B conn Medium Answer Type Questions Sop (6-128 t0 3-258) ‘A Concept Outline: PATE wuss § Long and Medium Answer Type Question imum Spanning Trees-Prin's and Kruskal’s Algorithms ingle Source Shortest Paths Dijstra'sand Blinan-Ford Algor ‘A.Coneept Outline: Part B.Long and Medium Answer S-1B(CSIT Sem) S2B(CSTTSems) oph Aboiy, ‘Divide and Conquer with Beomples buck at ‘soning Matris Mutplication, Convex Tl, Searching, GONGEPT OUTLINE : PART-1 ‘matrix multiplication 1 yy ecnique Soppse We wish 7 eae ageiti for mat Serpent de nd cone | sat ct C2 AP wher ath Ar B20 C ay te compat Rung ht iam eact owe Tears Sant nto a3 2 mato eee Ee cian teeta Vanoges | 1 SAE ret Seen BPS sanaleerthm or tee BES reat criscnduetd orreced gaps | {Sencar : «= BRS"GUa ese Sear I isso te searching a ata orenroied ost tbe ost rece, dioversd verter V. ype and Medium Anger Type Questions “Voag Anew 1 selection sort ‘GEE Write algorithm for bubble sort Bubble sort: Bate Sut) 1 fori to eng A 2 forj-tength Al dw tot 3 HAUL ope ay file 3] me Mennaieteant Serhaiech ae deter, eto 6 dete = 7 S24 thet Sra anes Siebivbne 6 3 user and rect rts Som (CeTT Sen.) evanteof at ofvertioes Vingther with aot of vertex es in F re imprtan bra ony ney linn argh apo orepresent ental any latina, a IN ines eves mene ac iatris representation : Matrices re ommenly wa o represent Matte or computer prosuing. Advantage er cnating he raph es te et a ny vere cane Shy applied ta seedy the stractral properties ef grap fom at ‘ecb oat vow. ae eo ae ee pre carat eeea ee Tepe nar open rete at me St nan ieee one ees Seg rena =e a, ain eh : aye tise wind others : “h Tncidence matic: 1 Representation otundireted raph ‘Consieranundreced rah = VB) wich vet lm hg al aed he nee nr 1) = by enn sai were Tye whmodgeginient with, 0 otherwise = S-6B(CSITSem5) Co Any Representation of rected raps " Haaren mati iD)» yo ErDHD with ‘Tosi te mn atin whi ri, se are jidirectd aay fom vertex, tare ie directed toward verte ootherite. 7 ‘2 Linked representation: crane represetatian te 0 odes ETUSLIES ao yg 1 Feroonomelehted ror, A Perweishtd [Renin [EE ‘here it isthe aeeny lta, th it of vertices adjacent for the corresponding node. rich ary 1b. Thebeadernoesin enchlist maintain alistof all adjacent Phtuolerwhich the beader node istmeant. FeeaT] What ina bipartite graph ? How to check grap bipartite or not? ‘Atprte gap ian udced graph G = (VB whlch Vee snort Ere ton se Yan Vp that (0) © ip er Peundec rw evjando-e Teche paps biparlie rno The lth ravers th gh RSE tere or? arrest ited parton nt rl one face dca btrecn foe vrs nthe sae Peron bein ers Bpareie.9 Pc echverer Mtl do Glows WRITE alee rtitna-0 Gta pay perstibiet Golet ae Wile ure @ est np do ue head (@] we {erected EBPO BPP Ae ee sd Ansys Algrithen pie Siero el prin hen fg. torn st 2B iCaTT Sem) 2 at) = WHITE hen coe 7 Soe} nl = purine ERQUEUECQ.) PEQueve (@ 3 pal = BLACK 3 nawat [Geass | Elin FS. As ve DSaeriin, rc OR pe Dopth First Search (DFS) stratgy. How DFS can be sed to Deere prabiem ofunbounded tees? Alo write ay algo an Algorithm: potion strts ta apie vertex Sle O, which comes creat » eres 2 Then algorithm traverse graph by any edge, «incident the eweent ‘4 theedge (oo) leads toanlreadyvstedvrcexu then we backtrack 44. Thon ther hand, edge (uo) leads oan unvsted vertex, then we go ooand v becomes our current vertex, 1 Weproeed inthis manner until wereachto "dade A thsi we arebacktracking ‘Theproces terminates when backtracking leads bcktothe ar were 1. Biges leeds to now vertex are caled dzorery or tre ges and ees Teadtoslready visto vertex are called beck eae ow to solve the problem of unbounded tree: 1 The problem of unbounded depth of tres ca be overcome by initng the depthirc search toe pre-determined dept init 2 Thismeans that nde at depth re tented asiftheyhaveno sass, ‘hin iscalled dept ited ware, Tis solves the problem otf ath problem. However, often we donot know the depth ofthe gal state, Ime ‘hoo 2 den we wil never Red the auton, we cheoe > me ‘aayend up ith a non-ptimal auton. BEERS a Pp SSB (CSIT-Sem-) Graph Abr, A Depuhfrt is a epeial ete of deputies scare, wheres, Atgorithm Seni ss desk inate “ a atleast tenet nation: = we gad cot 0 Tieton at ean Peet ph lit then ones praise nde ‘Spe nist ot of pede ‘BERET | lain Brenden Fret Search (BFS). Give ite algorithg, ae] ‘Breadth rst search: 1 genera de behind aroadh researc begining a starting ‘ue es fllows 1b Fistwecnaminethe starting node A. 1 Then weenamine all th nighbours ofA and soon 2 Nawal we ated to lop track ofthe neghboars of «nade, and ne ‘eed ogurantes that nde is processed more than once, 4 Tusisccomplished by sing aquevetobad nade that ar waiting ‘eprecesaed and by ung a eld STATUS which ls ste cure, etsy oe ‘Algorithm: This grit xeutes a resdth Set search on a graph tepining st ringed A. : 1 Inia deta ready state (STATUS. 2 Pat the sartng node Ain que and change ia status tothe wag a STATUS". Repent tps band ul ano tem 4 Remit fat de ef quae. Process Nand change the satel ‘Wate posed ets STATUS = 9) ‘Ato the rar fue al the eighbours of 9 tha are nthe es Sate (STATUSe1) and change Ur status to the wating se israrus-a. a cee {Endep} 6 Bd 93638. ] Explain topological sort Give it algorithm. sgn ant alysin of Agorithns Desi 29D (C8ITGem-5) Atoll ort ofa Diese Arye Grph DAG) Ginn dering she vertct of tach tht forvery dg ene we harp. 4 Avopsiscalsortisalinearorderingotaltavertcesnechheeont ju thenespeara baie nth rd warordeogispoe eH 3 Aleretrens eis name Sed thn fal Sorti@) [oF por each vertex ind the fish ine by cling DFSIGL, Insert och finished vertexint the front fink it, Si Returntholinked list, Write an algorithm to test whether given graph is connected oF not ‘Test-connected (0): ‘Choere a vertex: ‘Mae alist Lof vertices reachable roms), td another ist Kf vertices tobe explored Initially, L= Ks. hile isnonempty Find and remove some voter in foreach edge G, 2) leienotind) ‘Adds toboth Land 8. i€Lhan fewer thannitems 10. retum disconnected UL, elsereturn connected. EEBIET] Discus strorty connected compo aecthn. Tir Sg CnmcodCompnas (CC) rcd ph Cae Peeing arene een 2 teach trongy conned enpnet creed get, ee ety re efegcepehcedscoatnacet e rth Ai ston csarsem . evar tin e Keres anon ee ei a inardgepnnisteco eo tai alerts 2 Wile ert en atin Pero 809 rt ey Choose nabitrary verte nh the strongly conn nly connctay atest Buhne hat dp it search hes expanding a vere, rate, nthe transac grap, ant oo Atte tprertexcomS Performa depth rst search tring i The set ofvisited vertices will give the strongly connected ca : Dente pre ecm iter a BEE, mets ‘GeeR] Explain convex hull problems, on Discuss convex bul. Give Grabam-Sean algorithm to compute ‘convex hall “Tarwer 1 Thecomrerhllfasst Sof oitsinthe plane iedefined asthe smallest convex polo cetsining all the points ofS. ‘2 Thevertofthe cmverhullofaset Sof pints form a(not necessarily rope subset of 3: Techeck whether particular point pe Sis extreme ace cach posse ‘sat whether ples inthe range formed by thst mnand Analysis of Algorithms a eee een te esl oy CS). Coex al a amor at & Mess mevncnf mete sroneretsece tee verre shaman sgrithn are ORAAD-SCAN aa inp mt 9 of ins Ta BS eas theurtns To) whhreare ep arse 1 jtcnngne Santo NERO ORS pee Sete p of ace witout ange GRANAMESCANO) Pip tetera wie innuny adit elie Lek cae ta whore p> beth femsising rita @ ted ylang in 2 Let Uke onder sound ene soon ae sere moe lit tn we hates ae aust 9.9 Posy, PUSH, 5 frie atom do while the angle formed by pints NEXT-To-TORS, Top), and fakes anon eft turn. 7. oPORS) 8 PUSH, S) 10 return S ‘The worst case running time of GRAHAM.SCAN is Tin)» Ofn) On og ) + 04) + (0) = Of og) where n=1Q) (Graham's scan running time depends only onthe ie ofthe input tie Independent ofthe size tpt = “arvis's march computes the convex bull afa st @of points by steeigue oor as package wrapping. The algorithn ran ine O(n where min he number of vertices of CHL), Steps for Jarvie's March algorithm : | Fint, a base point p is selected, this isthe pint with the minimum sreoordinats, Sele attnst paint in cas ote, Jarvie's March algorithm to compute convex ll, ui cael Graph Atgy pearene im empty ie. solution set. poe nes oe eta e a Pies a, ibe LTH ena ns fo oe i line ns ie . naan ‘ a tomate ’ J ee ty a nen be : . 6 10 { a = 1 Anactity selection i the problem of scheduling a resource any oe Sonny ete Ds Bt ccececginmenteatt erro 2 mageeneerrne mtn Me, SoUtiemieplesy i ‘L- Thesctvtycleton problem is, to select a maximal sized subset 1 mutually compatible atviie, Here we masinize the number af stivities selected, but if he profit were ropartona o,f ths willnot maximize the profit i Greedy algorithm : Assume that fy. f, Greedy Activity Selector) fe lene Acta) Toads 67 8 8 Wi wii ime Fig 35, ‘The algorithm start with 1] and checks tooo which canbe added after, ‘updating the global “nishing time" and comparing with ech tart tine ‘The scivity picked is always the ist thats compatible, Greed algorithms donot always produce optimal solutions, Correctness: Greedy algorithm dos not ways produce opti elitons but GREEDY- ACTIVITY-SELECTOR does, ia GIG] What are greedy algorithms ? Finda solution to the following activity selection problem using greedy technique. The starting and finishing times of 11 activities are given as foo 2.8), 12)112,10 6,8) 0,000,061 6,8,8)6,9)(,10 ‘OR L 2 a 4 formeaton 5 doite,2f, 6 then A Ul) ‘What is greedy approach ? Weite an algorithm which uses this fem spproach. 8 retuma S16B(CSIT Sem) Greedy approach : Greedy seems rot promising at am ater "Activity selection". och eisai he ie ren on mu arene For exe consider he proj Cre Aor hae [Mewithn for gray activity sletion: Refer Q 8.5, Page 34, Uns “EERE stale 5 sofa teh] Wesel itary, ao (Check or stitya, ‘Startingtine fe, 2 tineote, 2 ey isnot eect heck oractvitye, ‘Starting tie ofa, 2 fish ime of, Gy iselected ‘Surtingtine ofa, 2 faishtine ofa, oot elected Ck stv, Suringtine cla, 2 fash ine fe, ¢sseleted Chet frst, Staringtine of, 2 fish tin ofa, oyiot elected Check tractivtye, Stxringtineofa, 2 faith tine ofa, rays, etme ‘Starting inet, 2 finish tine ofa, Conc NO Statingtine fa, finish tine ofa, Check ay, netted Strtingtine of,» Sihtine ofa, inet, Toerefar selected stv are: Anaya of Aerts LTB Cat Sem-5) rey oo 6D ew 02,19 a 7] what in “Greedy Algorth eee ore 0 a Feira Ce am me a rs yunasennn on et une pt dot en oma, ei a, ceca rates ee ees ach Feprene 1L-An optimization problem isthe problem of fading th best solution fomallfeesible solutions. 2 Optimisation problems canbe divided into to catagories depending ‘on whether the variables are continuous o diverts 8188 (CSTT-Sem-6) SP Ag cults oo can 70H Ta prenay et sen way in general that one cn #7 Sg * gemuamzonctmee rr 4 Humoee lwingepertoscen omonstan, probe towered er eee eoice property: A slbull ential outing Greedy hoe Pai optina greet choice, Ta, acrid hh ce to make, We make gee, ‘Tovlouteat inte creat problem, without considering fo sb robles. “ th. Oplnalvubsructure:A problem extbit pti stg, etna ta citn tothe problem contain within Ss eatneto so probleme = 1 knapsack problem ? Describe an a ‘TeCRTaT whee inapsaek Pore. sued to ole the problem. ae is ie tnpeak problem isa problem incombintaril opting 2 Guenase ftom, each wth weight anda vase determie ‘number each tem inde ina cllectionso that the total wei, ens han or equal f given limit and the ttal vale ie ase pose ‘It derives its name from the problem faced by someone whe ‘earned by a fixed-ize knapsack and must fill i withthe mo in kneeock problem, we have to fil the knapeack of capacity with apirensetoftems|; 1,1 having weighty u,v, inaucha manner {atthe total weight often cannot exceed the capacity ofkapans snd maximum possible value canbe obtained. 2. Using branch and bound approach, we have abound that none ofthe Stems ean have etal um more thn the capacity of knapsack and mst ive maximum posible value, ‘Tho implicit tee for this problem isd binary tree which let bean ‘implies inelsion and right exclusion 4 Upper bound of nde can be caleuated as: ubev+ 0 -w)(,lu,) weg valor ry ole a A ysinof Algorithms espe ao S19B(CSITSem.5) wel crete lnaprack problem, EB ete tnge tis et er cia ral Re encng ed ote a ae age ton lave tyne a: Bere current iter it, se + een staan rode nen cup problem fo th lwng nt xg ety eet tan ier sired mp ica | NET [va 1 fi te 2 2 i 3 ‘ te ‘ A 0 oes W=10 (olution This is als called 0-1 knepeack Either we can completely select. setts or skip it. First ofall we wil compute valueto-weght rato nd ep them in nneinereasing order ofthe rata tom [Weight | Value | ValuoWeight a 4 2 nas | + 1 a 49) 1 4 5 230) 6 + 2 a m2, “ ‘ofall the capacity W= 10, wo willhave 1 additem of weight 2 ahipitemof weight 7 8 additem of weight 5 4 hpitemot weight Maximum valve « 10.5 +6=165 ‘his the solution for given instance ofkaapsackproblen. atthe greedy algorithm doesnt give cpimal luton always rather there Inno upper bound on the asuracy of ppeorimate nto. OOP Alan Se ANRS NEA Ae a, BESET cient net ao, eh Trg tears Sr to act “ Freon | Weight | Value | Valuer, = =z |_| 0 7 2 o | » a ¢ | « | » 4 > ow | 4 2 z 0 1 F 10 2 ‘Weems use 0-1 knapeack problem when the items cannot be divi inn, ‘Riss and fincloalEnepsack problem when the items can be divided, frets. _Arsorng 0-1 knapsack problem, either we select an tem or reject, ‘Bolte willbe elated according to value pr weight. ® a ‘Bivsleced Busdlced Pissed Ceasot mated ease i We + 40~=110> 100 ease we lect D 10 2090-100 Tealvalse= 10455264 Acting tft Knpanek poten wo can slat fraction of any ten. Fuuced WoI0c100 Bisnlted 10.80, . 00 Pissed 0 Z70. 12867» ¥, Po vate, Tea] wees | Valeo | ValuorWeigne 711 Ey tole @ Toke peel ® a? | ® ¢ eres r T ‘ofall the capaity W= 10, A ites of weight 7. (naprack apcity = 10-7 = 3) ‘Skipitemof weight 6 lace svallabe knapsack capacity is es than 6. ‘Skipitem of weight since avalabe knapsack capacity is ‘Add ite of eight 2. Capac capacity =3-2= 1) Additem of weight. Masur Value = 198 1261 =o REESE] Consider toliowing instance for simple knapsack problem. Fad the solation wing greedy method. PstI 21,81,83,4,69,55,65) 1 11,31, 25, 85,49, 45 55) cree inof Algorithin jqnand Ava pa San BcsiT-sem5) 1B, 28,83 4,45 5) We ia 84,5, 0 wees the value of Pn decreasing oder oN Wm F f 7 7 1 3 a a 5 2 Ff 4 2 5 5 6 149 é S 3 is 7 6 & an 8 LJ os 3575, ser te knapeckacrering ocean vals P Fis me se New e1wooe welt is ea tem 2 wha weigh Ten hee em BY = whe woh 21 Jen ore tem N= whose wight 23 Now Gee iem 8 whe eh 38 Be ie in nepreein= Ds 22339 =69 aa teat tems = enditwigh nab we sx 21 cree Tit Athos factional profi, Saleen peel 263, 218 1-103 o a @ 7 = ue ‘Tha, the maximum vale m Shaan 65 789-1419 + 8 Taise 4B (CST Sem) Gr Ate saenecares? ____—_——____~——\ GONGEPT GUTLINE : PART-3 ning Ani es Bic etal everest nah | sy mse 1 BETTE peo techniques fading mlninee spannin Nak ee as ollows te «Bite souree ahortest paths problem : Given Single argc ent tind a shortest path from a given eon | "yt avery vertex ve KEEEBE] nt do you mean by spanning tree and minimus seoning tee? aa] Spanning tree: pang te of . contin ing gh not arog tact al “hati apanaig re ofaconected graph Gcontainall he veto tad ha th ees wich oon l fhe vere oy the number e veil Leste number of nodes : ernment aves adie 4. Apap may hare my panning pang es. Minin satin es ve nected weed graph ine. nid weed graph, itis ten desired nese Bente Cuchi eum the wept hte 2 a | a x pnelyin of Algoithens pose Fach are cle ¢ minima oanig Sue yoann al thee nC “seer eral gn cig stam pasa 2 Becwnctge ae wane ee a a ecient GEERT We Ht eth ne pig Ta ye hn ne oh bas mae Ie erg od whieh ae ts viet aa in Geren hah sd orn en Rasa te cnaiowane eee horas required: Ty chcney anf rh eh Se et ce dete saeten el eaten ireanot already chosen such that i 1 eee hn ey. eae ot jaan ti uepss {20 ars verte, perm = ao onary aan tote weet omnia he ih of dee a Lote en Face napa tnd Social ae Fi clltnepesinre Describe and compare following Aeemine then cor spnnin ee: fesquteay deostin 1b Pens ago {eRe algo eer 925, Poe 2-258, Us iL Prim algorithm Ponce ered then eer and ithe wih TORS ens te lgitimiandverobwne st hep Chne ny ester Ye ‘nd representa the le isassoall rithms to (ARTO 019-14 Maes 1] ap, eww an eee NV G0 MEV have bon chOS avai oat aed = VV vith VY, 1 Mi, Wetec eka ert gy surg tth precisely one end in Vy, Vet mg pesiop afer n= 18H Have Been SHOE. Other, Bens 7 Comparison She] Ranta agortba [UPAR algo rithm | Pris algorithm iniaieyso) rrthanedse. [node a) — FZ Tavecatsalgortio selects] Prints algorithms span [Erkan way tat te node to another. osiion of the edge is nat asd the last sen. [Tiras can fantion on In pris algorithm, graph mang [isonet grphstoo. [a connected graph ete monde sgn on Ane) o— From an] [Lanka's time complexity |Prim’s algorithm has a ting] iow we lok on weight at es Saray [coupes in wore ews ra. B)=4 ants Monee moles I WD, d= 6 choot e = AB since itis minimum, ‘Gara ] what do you mean by minimum spanning tree? Westaycan also be chosen beeause it has same value, ‘an algorithm for minimum spanning tree that may generate ‘altiple forest trees and also explain with suitable example. (ARTO SOE Marks) ‘Minimum spanning tree: Refer @. 8.25, Page 8-24B, Units. Prim'r algorithm :Refer Q. 327, Page 3-258, Unit-3 Example: Aecoinglgithm we ios vertex fom the et AB, 0.2.5 mD.D=6 We cote ¢ = BC since it has minimum vale

You might also like