0% found this document useful (0 votes)
86 views32 pages

DAA - Work Book

Uploaded by

Mahesh Balla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
86 views32 pages

DAA - Work Book

Uploaded by

Mahesh Balla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 32
Student 1D. 220008014 4 Student Name . | V-Hoxi Zankow 1 Analysis of Time and Space Complexity of Algorithms quisit Basics of Data Structures and C Programming. Basic knowledge about algorithms in C and Data Structures. ing lockdown Mothi gets bored by his daily routine while scrolling youtube he found an rithm that looks different Mothi is very crazy about algorithms, but he cannot solve algorithms multiple loops so that he structed and need your help to find the time complexityof that orithm oritm KLU(int a) int count=0; for(int i=O;i0;j=)/3) { for(int k=O:ko * 58 ola [e Ken! Coumt 4 >! kt tt j= oe | paiut C Numbers of Hexoxions: count) def rreinl): ne fan Cinpust ("Ewer A Vole foe's +”) kLuUtN) Ch _- Win - >2 ya - win) “Tirge Complerity:— © (n (og ny?) Klaus Michaclson is interviewer, so he prepared a bunch of questions for the students, He focused on algorithms. Among all the questions the easiest question is what is the time complexity of the following C function is so can answer to this int recursivetint n) iftn==1) return (1); else return(recursive (n-1) + recursive (n-1));} Ky 0") teh em): Thowerkt retucn 2 : any KOCLNLVE (w-i) ¢ yecurgive nt) chun es cauangive CS) m we, wegulk) ke SourseT © | DESIGN AND ANALYSIS OF AL‘ ‘ourse Code(s) OSPR 20C52205A/P/R An =Lab: nm Input You Outp You Source code: [Course tit = eee DESIGN AND ANALYSIS OF ALGORITHM Caroline Forbes is an intellig comples. problems so. Ew accordine to string lengths, Hf you are smarter than her, try to solve the problem fa 1 girl, every time she wins in any contest or programme, and solves nge problem that is. Sort an array of strings er than her? 1 10 give her a chal are beautiful looking are looking beautiful crt. by levgttars): orted — O%% = 4 ested (avs key ler) sont - Asd loeautigal Inoking ou Oxe x. SOO) angus, es Spi leva CNP ase) Sort _ bor = (outer Owe) ACADEMIC YEAR: pa Cone(s) | 20€82205A//R Page 8 of 126 2) During the final skill exam teacher was given a problem and asked everyone to write the algorithm to it, and advised that try to implement a different approach from others, Question: Write an algorithm to calculate sum of first 'n' natural numbers Mothi, one of the student in the class thinking that his friends will write an efficient algorithm to that question. So, he wants writes a worst approach to make that algorithm as unique. So, the task is to find whether the algorithm written by Mothi for sum of first 'n’ natural numbers is correct or not and analyze its time complexity, bers Algorithm written by Mothi for Mothisum of first ‘n* natural nu Algorithm SumOfNNaturalNums(int n) t int count=0; i<=nji++) return count; Source code: - oe (2 SamokNeduaclNums 1) + Cour? O ae aa Lox tin sage C ' for ft vouge Court th neds CseOe vetusn cout Sum of Natuval™ earnstn) Say “natal nuMber Ss! vege ett peiuct CM Sum othe Fst" 1. Course Title DESIGN AND ANAL S | ACADEN a 2 Course Tt DESIGN AND ANALYSIS OF ALGORITHM ACADEMIC YEAR: 2023-24 | Course Code(s)" 20¢S2205A/P/R ae 9 0126 | oie Durinw the final skill exam teacher was given a problem and asked everyone to write the algorithm to it, and advised that try to implement a different approach from others Question: Write an algorithm to calculate sum of first'n’ natural numbers Mothi, one of the student in the class thinking that his friends will write an efficient algorithm to that question, So, he Wants to write a worst approach to make that algorithm as unique. Algorithm. Algorithm SumOfN Natur: int count=0; Nums(int n) count++: } return count; urce code: ef SumOF Notasal Nue wd: Comma 0 i tw weuge G,yntt) Soy j tn verge fay cociwt =h for we. xetusn comm v ' hums) ’ Se Joerg: weg) “ apctural humbers: -de8 pesuct Ceaen ate fevat 7s WO Ay { Course Tite DESIGN AND ANALYSIS OF ALGORITHM | 20CS2205A/P/R — 7c | | Course cog __ ACADEMIC YEAR: 202. Page 10 of 126 Post-Lab: InKLU streets we have lots of electrical poles. Note: all poles are sorted with respective to their heights. Professor Stefan given the H = height of one pole to Mothi then asked him to print the position of that pole, here We consider index as a position. Mothi is particularly good at algorithms, so he written srithm to find that position. But he is extremely poor at finding time complexity. Your task is ur friend Mothi to analyze the time complexity (all 3 cases) of the given problem Int Binary Search (int a, int low, int high, int tar) int mid: if Uow > high) retum 0: mid = floor{(low ~ high)2) if (a{mid] == tar) etum mid: almid]) Binary Search (a, low, mid-1. tar) retum Binary Search (a, mid~1. high, tar) Source code: + cage: OO) . Case OL Ley n) Cage ~ Ol Ley, ") cganela Ca Low ig hax? ce few Peigh? aeturn -\ oid, (Lowel Ev afmnid Jee a mid ole neckus ae eed . . ie . Biwony Searels Cor for mid ote ~ cb peturn Binary fears Cain titan) pazgh, Ar) are Cit pat, Mth) vt wot found’) aise? Co Eterm NANO ANALYSIS OF ALGORITHM _ACADEMIC YEAR: 2023.24 DSAie Ree "Page 121 126 a . © Student 1D ae a 1 Siadent Name " £X—2 Implementation of String Matching Algorithms oo Prerequisites: «Basics of Data Structures and C Programming. «Basic knowledge about String Data type. Pre-Lab: Given a pattern of length- 5 window, find the valid match in the given text by step-by-step process using Robin-Karp algorithm Pattern: 21936 Modulus: 21 Index: 01 234567891011 12 13 1415 16 17 18 19 2021 Tests 92721830571 21219362397 ecode: le € calean KospCpaktert text, Mmodulugs ' —_ xtkowny value & = Cova char) fox cay tn po at yatuess Lovaccher) Por chor atest) ] : be pecttern hare > sum Clvalue £ (models oc Cpetkewnd —i-1)9) ate Modes for =, Value i0 — exrecte (partern - VOEHE Sy]. -6 oe : neler trashs gum({ (vatue ae * * Q1@R6" bore: “QD etsto5t TEIBtaegr” modulus > 2 revoe sve paaneptranienn text rmenksive) fe cle ts eaivek Cabict @nccree found oe oe qubgheivgs” reore Cinder Index fen Cyr) ie privet CON! valid patel Round -”) DFSIGN AND ANALYSI a D LYSIS OF ALGORITI 052205 A/P/R HM EAR: 2025-2) ee ____ Page 16 of 126 50 Contels) cuss the Rabin Karp algorithm for string matching and explain time complexity of the algorithm? def wabin- Kasp-feaxch Cpattesn rhext)s Qeime = (ol m= fen (parte any + fen Cert) es Wag seugit ; hash value tO Bor de Ty Kenge Clevgi Hite Ord SUDYE PAE Vag. values (vor Betuam Wash value patios — hag = calerloke hag a(pattern ro) tot ass calcutette Lhastactext. to) fox Tin paygeCr-me0t i€ teat legis patron hash + UE tot Lirtemy 27 Peern® wetusn 1 Te Tans ext laghe Ltext- Wash tort rag: Hert bash. ie text rash 40° toxt - raph Och Hex LID) “f Poerre pacdttert (iene D>f painne 42 prime retuan ot Prox 1226 Bort = Moyen Ta OSAMA TRITON © wedex = ral pr. bonp. search (pattern tert) my led munich feund at waders’ . Creter) *, fext [ardecs idost Sen(gattrn] (Matched gubstetug: NAND Al patierntj3* fprak fezt we farm: 4 “ spars dation fons a a! gen cock (tet 1, poet i.) ACAADAALA ABA™ ACL . Aw nove pe ing. Sec eta tart? 1 Pl?) CourseTitle bis : Coune Te DESIGN AND ANALYSIS OF ALGORITHM ACADEMIC YEAR: 2023-24 20CS2205A/0/R Page 20 of 126 Postbus 1) Givena pattern of length: $ window, fi ons, find the valid ma © Soa aaa ae match in the given text by step-by-step process Pattern: 21936 Modulus: 21 Indes O12 3456789101112 13 41S 1617 18 19.2021 Source code: S072 oor g ap Chet (Pouiesy) Pmncclbugs? + Tintc) fox ae ty petliesn 4 ey text pit yj ek Cfon(ptiesn walhin. KASP arn Vales = Tit Od few Crate #CM0 Aulus def path vatues = yatlosn trash = 6umcC elues) EY) i oh on tei tone. Magte Surn(LCveuMe e(encctubg ® Fann CpeHeMD _ yale g)-1- DY 3s) Gent peoee sn Vala’) fox T tin savge Coen ttert vabue q thon rash ! ston values) i coirclote ~ bash 2° TH text-values Cert ¢ tent 22 patiesn VAMOS * parear (Vallis pect c foruna oct inden 2”, t) TE < Rervetert values) = ten cpetean-vatues® Lag th = ff coireloro bash Je tmodabus © €(gen(qetdenn ch. Valuer town ics ~ thert values C cycled) A199) Rmcatlus ete Tes Jortpcetern- v clue §Y)) of mecklug ee ee DAO RTOS FH LDL DIABEIB IU, wi ffeek fatlern, moceleaty o!ON-AND ANy Scoop AMAUISISOF ALGORITHM | __ACADENC YEAR: 2023-24 paige ce eee eee | 23 0f 126 Valid duct found at idler | obid morc found at index 1 >) James is sharing his information with his friend secretly in a chat. But he thinks that message should not understandable fo anyone only for him and his friend. So he sent the message in the follewing format Input alb2eidte Output abbdetdhe tion is are replaced as follows shila} tb! shificb.2) shit’e3) =P shilt(d'A) =" bE laa Cola Stift)® Lor. iealea O* bage: owaa"yte © ctu clartlowckC Cow) “Warde sabi ouetAT) Lav.ishouse re) kee ord A et) -}. 2b + ecu?) seek CON dee crcnet _reeesage COMA EE)” oudpot U3 eviet = \ Boy cluor anped E> - i cca aE) utp append tas jet clay eft et Re cute! ike un Sle je nCouteur) ap bh © Aue Week. SUF i ey ect rrergeg? (Np Ste) eee om) IGN AND ANALYSIS OF ALGORITHM } ACADEMIC YEAR: 2023.24 20CS2205A/0/R I Page 24 of 126 J — i | Student 1D | tae | Tudor Name} FX 3 Implementing Programs on Sorting Prerequisites: 4 Basics of Data Structures and C Programming «Basic knowledge about Sorting Techniques. Bee-Lab: 1) Write a Divide and Conquer algorithm for finding the maximum and minimum in the sequence of numbers. Find the time complexity. ded Find max min lors , tart pra): if tast=send: WELUSN HE catort] ,avv Cota Ck ovct- fravt 221° i ie Sawn xoturn (asst Aor] rows teva) & ay [orart] 2 ave Cenc} coal alee Cows feuct), aratetartd) ete: rid = Cotart ¢ end) I/? Tray leet, min. Wf find ahs Peed. reve enin( Orn richer y preak ni n(ary, save reed) nak KIWI, rine \ 4 f Oned) rectus m peer rea left MOK ~ wigler), pin ( for ted t it) : i course Title foesew AND ANALYSIS OF ALGORITHM | ACADEMIC YEAR: 2023-24 wurse Code(s) | 20€52205A/P/R | Page 27 of 126 | ees eee pri nn gall de® mak_ min = sequence (ax) + i not ors. Yetusn None,None Wettam find —mas_tMrin(arr ,0,Cenlary)~t) Requence > [3,5,28 14,6, uy MOK val Mineval + Moe men ~Sequence [eequence) Put(’Maximun values”, Mar vat) Pit Minimum values", men. vat) 2) Writea divide and conquer algorithm for finding the maximum and minimum in the sequence of numbers. Find the time complexity. Source code: LeMAX — Min Cams -Stast end) + Ast 2 Fett? sctusn Ass Cater std Aer Fatart] Oucl - stews st tt Yeteawny Cae [Start] ,ABs feral) EF Aor Eeteurt] Zarek elge Cary Lend se Tsterst J) ria = Cotasceensdif » : ie toast pid) pax feet tein keft = Baad mraraersin (re SP a max _ wight amin. right > Bind rere Co NOSS peice tf syctuan max (mex left, eax wight) pian Conin. Cet, min sight) Sef rnax - main Fogquence (ar) t net Ass. xcturn None Nore n SAN etn Rud moar - min (A¥¥ 0 lencary ) sequence + CEr5/ 218 WGI : 7 agence (SEG ver C& o a eke mon-ce ee nee (24 pret ( Marimum Velie 27 har val) oat Co Minimur Values) min val) \ Course Title | DESIGN AND A ae [coun eadent DESIGN AND ANALYSIS OF ALGORITHM | __ ACADEMIC YEAR: 2023-24 | am 2OCS2205A/P/R ae "Page 28 of 126 | — Indu: fy Harrys Aunt and family treat him badly and make him work all the time. Dudley, his cousin got homework from school and he as usual handed it over to Harry but Harry has a lot of work and his own homework to do. otk is to solve the problems which are numbered in numerical he tries to solve random question after solving random questions he did not put those questions in order Dudley will return ina time of n*logn Harry has to arrange them as soon as possible. Help Harry to solve this problem so that he can go on and do his own homework. Example put The home 9 15,5,24,8,1,3,16,10,20 Output 1,3, 5, 8, 10, 15, 16, 20, 24 Source code: Vek merge geek (axe) * te Lento) c='! retum Orr mid + den lorry We tee olf 282 {mid mide vale = orre[enid 3 4 Val = rrevpe gent (ef Uol? 5 sgt bole > Wrevge Sot Crit elt) ae ies balf) Somtect_are2 Merge Cte pe Lrcilf , VIA xctusn goed O87 £ ererpe (Left eigit)* 1 evget= CI ; tebe. tnete xe, wight - index 01° ae Noke FX Linder 2 fencte £1) ant vigltt -in 2 bon Cig: ee Tek Lept-inder] 4 * igi veered eager Coeee [ Left inctery) Meee incor Ft faigha- ince] * ve ee : exc append Crighst Cnig index 1) pith se chANO) mergect tinder 42 f Ses, & 2M 8, 1B ler 10,20" gence. Std = in pert - sts tt C19) Coats Ciel ay For x sees SeAcCENp ot Lis egtious > MENTE questtous y) aentod Tete, Sortect ~ eecipet ates). goinlws peint Ceuper - ats) t Course Title DESIGN AND ANALYSIS OF ALGORITHM. Course Co 8) 20€82205A/P/R a ras td, taeieeels C3.4], cos sey T3489) yc 04,464 peed, pst, Crd pau tered, as 36, 5U48, ug, Tr ba ASI, ra 4, tga, 36 eatt 24, 34,36 Gre Gar) as ACADEMIC as 2023-24 | ge 32 0126 Chis and Scarlett were playing a block sorting game where Seartet challenged Chris that he has tosort the jocks which arranged m random order, And Searlett puts a restriction that he should not use reference of first, median and last blocks to sort, and afler sorting one block with reference to other block, for next iteration he must choose another block as the reference not the same block (random pivot) Now, Chris wants help from you to sort the blocks. He wanted to sort them in a least time. Help him with the least time complexity sorting algorithm: Input format First line of input contains the number of test cases. Neat (lines of input contain The number of blocks provided by Si The array of blocks. Source code: impos sandem iti o Ligd: de! stition( awe , Loto Lt g) : wy = pevot - index > sanclom «yank wet ( Povo, Wg pivet.value > as [pivet - fndex ax [pivet- Intex, arse gute axvlvight, ant pivt- iced t: Low Rev jin marge (Boa terg)* ef canna 2 pivot vane ® 7 aol C2 asl T= ev wy arti t4e\ any (i), 9 Lacgay sare[hight, a> Wh svetusn t fc ee sn Loran righ): bee warden ved . quric h-fOt CAB + c 3 fe ferod aight ie vivek inden: pantitiontos Lovo igh) daw clennizzect quite somlare, lora,pivel- inden 1) gancemiizect. quick. somt(ann, peut nck Wa) PAC Eder tte Nore} “loth cages." YY for 2 in yauige CL) = Course Code(s) | 20€82205A/ use Title | DESIGN AND ANALYSIS OF ALGORITHM | aoe ea bese tclocte gs List (rap iat IMpUd spl) dandomirzed. quick-soxt [block $ 0/0 ~1) Priv (“foxted blocks: ", blacks’) wo 4 Student ID Student Name EX —4 Application of Strassen’s Matrix Multiplication and Convex Hull Prerequisites: * Basics of Data Structures and C Programming. Basic knowledge about Matrix Multiplication. PreLab: 1) Trace the output of the following matrix multiplication using Strassen’s Multiplication Method A. Band C are the Matrices of Size NXN a,b, cand d are the sub-Matrices of A of size N24N2 and h are the sub-Matrices of B of size N/24N/2 Source code: impast NUMpPY Ob RYO fof stansgen - enctigoe -MUtiply (ane). ns A-chapelo] fo mechs tian A*p mid: Nflo atts Af imich Mid] ata. A Cimidimiat) (Course Title Z _ DESIGN AND ANALYSIS OF ALGORITHM. |__ACADEMIC YEAR: 2023-24 | Course Code| 0CS2205A/P/R Paye 35 of 126 He ast Atenid tri) 92. A Conia: trict] bins BLmid, MIA] eras @LEMid mide J oat + Blmict: mic} 22 + Blmid. mid=] Pr = Steaugen _erethein- ro libigy fair tot 23) 25° FUMSIEN - raha ~ coultio fatt¢are 22) pas gteaggen. tratteix _erelinly (0914022 70") eu satronen mata PUL DYy (as2 pp2t- Ul) fc: stmgen- ecetteine — rreubtiglsy COUtFO22 a4 22) fe: pacngen -rpattaize -evttipty | ony 22 , 21422) pr: trae. ratte -muligy Catt as) ptt4let2) ett: PS 29 -prerG Cras POF PE cars P2e OF C22 2 PteeeP2-PA c: mnp-vgtenck Corp: bastenek (FEC, Dp -fistack ((¢2!, 2299) Yer C As np -ABxe Cttyet ts.) Be HF away cttsr63, (4,891) Yesult: Srawen. morte - 7t LLtihy (Are) pricat (rogult) [Course Title T pesen> Course Conkolgy TO ESIGN AND ANA jurse Code(s) "1 dope NALS In-Labi You are given 2 matrices of any size N¢N, Wri aries NEN. Write a pro fi (use Strassen's Matrix Multiplication), eta A Source code: impost HUMPY cue np Yok FRANKEN. rete _rmubtiphy tai: iE A-ghage [o]= 213 yettan A*R re A- shape fod If aye ato, th] Ate > atin ay art ATHE 89) aor= Amr, Ne) pres Aten od pra. @tinnsy pore [ns coral boo: @[ns 08] streets x cnultiply(at! £022 Pollt b27) <2 hoargern. reds - NU (cx) 02> out) mahi uf att, B12 629) brt-bi) Plz stwMaen p32 > ateaen. mnctatx - PU Styenger- mrautetic - roeelghy Coae? : Pe > etraagen - MAB reeattiply/ oyna? 1P2? PE > gtacater. Maly - mmutliplyras att birebly P2-> gtaaoyen. mreantoix - mo rtipty Cap-aszs 21th?) etre CE PU PSAOT Cin + Ps ets cop. P2404 Cars PI-P24O2 4h [Course Title DESIGN AND ANALYSIS OF ALGORITHM _ Course Code(s) | 20€S2205A/P/R ts pgevstck(CMpUstack (Cem, e299 pmip- baste €7 1/2298) geican ¢ As Oparray ced, ts.4ay) ge Mprowady ( rts,67,0a.s wesutle sexu gen Pretaie MakEplylA 1B) pat coegtut ) Mr. Hart Kumar owns a fruit im el ¢ y M narket, In the market there are many sellers who are selling many Jinds of fruity, More than one fruits seller can sell same kind of fruit, Mr, Hari Kumar wants to arrange their information in the sorted order based on their names of the sellers and id of the fruits You must arrange the same type of fruits in the same order as original order. (-mangoes J-apples, (Hint: Use counting sort algorithm] Input 4 {(0,c}. (1, 6}, (0, a}, (1, 4} Output (0, a}, 9, ¢}, {1, b}. (1, Source code: def COUNTRY - feist Mate (D8) rn: Len lowe) rrax ids Max(iteml Count 2 [03 *(trax. id 41) Oulpa = Coy * £px Hom in ase: ecu Titemp ID] 4=! eC man ides C1 fos Kem in Ars) for i in xoug Cecest (Jez coud Cet] fo, Lorn in KeNS y ged (x8) ; cep froura Cite tS“ s ftom Couva Cite] >=! chun outp ect Yeu a i we (tered, [1'b'7, 101% odd) Fruits lors) Fortoch. avs > COUY aS peat Gsortect 02%) ACADEMIC reas | Course Title | DESIGN AND ANALYSIS OF ALGORITHM = Page 42 of 126 [Gourse Code(s) | 20¢82205a/P/R

You might also like