0% found this document useful (0 votes)
72 views134 pages

Daa

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)
72 views134 pages

Daa

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/ 134
Fourth Semester B.E. Degree Examination CBCS - Model Question Paper - 1 DESIGN AND ANALYSIS OF ALGORITHMS rime: 3 Hs Max. Marks: 100 Note : Answer any FIVE full questions, selecting ONE full question from each module. MODULE - 1 1, ». What is an algorithm? What are the properties of an algorithm. Explain with example. (06 Marks) ‘Ans. Algorithm is a sequence of unambiguous instructions for solving a problem i.e., for obtaining a required output for any legitimate input in a finite amount of time. Problem Algorithm Input Output Properties of an Algorithm : An algorithm satisfy the following criteria i, Input : Each algorithm should have zero or more inputs. The range of inputs for which algorithm works should be satisfied. ~ Output : The algorithm should produce correct results. At least one output has to be produce. iii. Definiteness : Each instruction should be clear and unambiguous. iv. Effectiveness : The instruction should be clear simple and should transform the given input to the desired output. Example : Algorithm to find GCD of two member. Euclid’s algorithm compute GCD (m,n) Step 1 : If n=0 return the value of m as the answer and stop; otherwise, proceed to step - 2. Step 2: Divide m by n and assign the value of remainder to r. Step 3 : Assign the value of n to m and the value of r to n. Goto step |. & . Define three Asymptotic notations with an example. (06 Marks) Ans. The order of growth of an algorithm’s basic operations count as the principal indicator of the algorithm’s efficiency. To compare and rank such orders of growth, there are three notations use. i. O (big oh) ii, 2 (big omega) iii, 6 (big theta) Sanstar Exam Scanner 3 CEE IV Sem (CSE / ISE) Design and Analysix of Algor, 1. O(big- oh) notation : A function {(n) is said to be in O(g(n)) denoted i iru i ‘ted above by some constant multiple of g(n) for all large a fs Oey some positive constant ¢ and some nonnegative integer n, such that, ere Skigg t(n) se g(n) for all n2n, cis positive constant \ n, is nonnegative number extn) \ t(n) Example : (n) = 100n+5 € O(n") 100n + 5.< 100n + 5n= 105n for alln>1 Where c= 105 n=l ii. 2(Big-Omega) : A function t(n) is said to be in 2(8(n )) denoted t(n) € 2 (g(ny) If t(n) is bounded below by some positive constant multiple of g(n) for all large n, ie., if there exist some positive constant c and some non-negative integer n, . t(n) > g(n) for alln2n, Example t(n) =n? ‘ t(n)>c. g(n) v2 for alln20 ie., c=1&n,=0 ne Q(n’) , a, A iii. © (big-theta) : A function t(n) is said to be in Og(n), denoted t(n) € @ g(n) for all leage n, ie., if there exist some positive constant c, and c, and some non negative integer no such that ¢, a(n) $t(n) 2 ence 20(n-1)e8(0") ‘Where © =H =jandn, =2 Design an algorithm to search an elenwent in a array using sequential search. Discuss the worst case, best case and average case efficiency of this algorithm. (08 Marks) ° bs ALGORITHM SequentialSearch2(A[0.n}) K) Mmplements sequential search with a search key asa sentinel Minput: An array A of n elements and a search key K /Output: The index of the first element in A[0..n- 1] whose value is I equal to K or- | ifno such element is found Aln] — K ied while A[i] # K do ieitl ifi is defined by pair of fwo sets. Vis finite set of vertices Eis finite set of edges | O—@ Undirected Graph : If every edge in the graph is undirected. Example : @ © G=1 T()=1 ii. T(o) = T(-1) +1 forn>1 TO=1 (08 Marks) Ans, 1 if(n=1) (M()= 1(3) +n Otherwise Consider the relation 7 Suistar Exam Scanner Se nisr(2) : | woh tata wae — GhOs a), 0 My ee others Ty toget terminal condition let2'=n rere Tlo)=1()e rt gge rae WhereT(I) =! To)=te ts padtaer S14 2b 242 tt 222TH 2! 2" 1) .byseriegrule a2 [222-1 den [T(n) =2n -1 i Tla)= 0 if(n= (iT (9) {ete pil T(n)=1-T(n-1) Using repeated subtitution as T(n)=1+T(n-1) =l+(I+T(n-2)) =24(I4T(n-3)) =34+(14T(n- Foti, substitution | T()=i+T(0~)) Leti=n Shay Exe © Ass. write Igorithm to find the maximum element in an array of n elements. Give the mathematical analysis of this non-recursive algorithm. (04 Marks) ALGORITHM Max Element(A(0..1 ~ 1) Determines the value of the largest element in a given array Mnput: An array A[0..n ~ 1] of real numbers Output: The value of the largest element in A maxvale A[0] fori | ton-1do if A[i] >maxval maxval+ A[i] retum maxval Let us denote C(n) the number of times this comparison is executed and try to find a formula expressing it as a function of size n. The algorithm makes one comparison on each execution of the loop, which is repeated for each value of the loop’s variable i within the bounds | and n — | inclusive. Therefore, we get the following sum for C(n): 2-1 cla) l= This is an easy sum to compute because it is nothing other than | repeated n— I times. Thus, C(n) "1 =n-1<0(n) MODULE -2 3, a. Explain quick sort algorithm. Find the time complexity of quicksort for Bestcase, worstcase and average case. (08 Marks) Ans, ALGORITHM Quicksort(A[L..r]) // input A subarray A[L..r] of A(0. Land rare left and right indices // output subarray A(L...r] sorted in order ifl= ALi]) do j — j-1 while (key < AU) if (i1 Copy A(0..[1/2] - 1] to B[O.,[r/2] -1] Copy A [0..n/2] .. n-1] to C[0..[n/2] - 1] Mergsort(B(0..[n/2]-1) Mergesort (C[0..[n/2]-1) Merg(B,C,A) ALGORITHM Merge(B(0..p-1], [0..q-1], A[0..p+q-1] i-0;j-0;k-0 while i

T(I)=0 using substitution method Toe (1) = 8(n tog") b. Give the pseudocode for finding minimum and maximum element in an array of ‘n’ number using divide and conquer method. (08 Marks) Ans. ALGORITHM Min Max (ig,maxymin) if (=) then min = max = afi] j=!) then if Qi] < aff) then { max = af]; min = afi]) else max = afi) ; min = afj] else ity id =—=; aaa MaxMin(i,mid,max,min) MaxMin(mid+1j,maxt mint) if (max < max!) then max = max; if (min> mint) then min = mint Swnstar Exam Santor ee 00s - Model Question Paper - 1 einey To) =[*T02)*2 wl Ten) € n) c. Apply Strasse matrix multiplication to multiply following matrices. Discuss how this method is better than direct matrix multiplication method. (04 Marks) CH ce HC The components of the matrix C is calculated as: Gy) = 8, XD, +8). XD, =4x243%x1=843=11 x5+3x6=20418=38 a) X Dy, +g, X By, = 2X24 1x1 = 44125 2) X Diy + yy X Dy =2X541x6= 10+ 6=16 1B j2 +)3 Dy From the above resultant matrix, we can notice that Strassen’s matrix require 8 multiplication and 4 addition. Where as in traditional way it requires more. MODULE -3 data. (08 Marks) 2 | 0.15 5, a. Construct a Huffman code for the follo i, Encode the text ABAC ABAD using generated code ii. Decode the text whose encoding is 1001011100101 [0.1 015} [02] [02s B E Lo] c Cd 0.2 0.25 0.1 0.15 D B Sanstar Exam Scanner 15 [Probably | 04 | 0.1 | [coterd [1 [roof ot [oo [101] (Encode Text-1T1 001 101111001100 (i) Decode - 1 00.01 01 11 00 101 BCCADE b. Arey PRIM's algorithm forthe following graph to final Ce oF 16 ee cBCs * Model Question Paper - 1 sso Ren Vx ar) (8,3) c(-0)d(, co) e(a,b), fla,5) Ans cS pare heapsort algorithm to sort the following numbers. (04 Marks) Ans. Stage \(heap construction) wonnn anoves eo co co Ranaan 5 5 5 5 5 aia rr © Sunstar Exam Scanner 17 Ans. Using feasibility rule Ans. Four feasible solutions are [Solutions T(x, x..x,) Desig CAR ANDY OF aii IV Sem (CSE / ISE) Stage 2 (Maximum addition) 9 6 8 2 5 7 7 6 6 2 59 | $6 2 2 5 5S 6 7 2\8 76. 5 2 2 6 5/7 6 2 5 5 216 52 2 2 Sorted elements are 2,5,6,7,8,9 OR 6. a. What is the solution generated by the function job scheduling when n 5 15] = [2,2,1,3,3] (06 Marig [P,)P,, P,, Py Py] = [20,15,10,5,1] and [d,, d,, dy dy d, Job considered] Action i assign to [1,2] Q none {1,2} [0,1},[1,2] 3 cannot fit ra a {1,2,4} | [0,1],[1,2],[2,3] ju 40 The optimal solution is j = {1,2,4} with profit = 40 Assigned job b. Solve following instance of knapsack problem using greedy algorithm knapsack (06 Maris) weight M = 20. Pr fans] 163] 2425] 2 [sf it.1y | 20 [an] Solution 4 yields maximum profit item (0,1,1/2) and profit 31.5. Sunstar Exam Scanner a os: Model Question Paper . 1 te Dijk Writ nm Dijkstra (G,S) ‘Ass input : A weighted graph G = wi — , es tthe length dv ofa short ith nonnegative weights and its vertex S. vertex vin V. t Path s to v and its penultimate vertex pu for every . initialize (Q) ; for every vertex v in V do dee Py null insert (Q,Vidv) initialize vertex Priority ds<- 0 Decrease (Q,5,d.) // update Priority v,-Q fori 0to|V|- I do ut deleteMin(Q) // delete min Vv, V, U{us} ut do ifdu+ (ut, u) 1, F(0) = 0, F(1)=cl. OR For a given graph obtain single source shortest path using Bellman ford algorithm. (10 Marks) Sunstav Exam Scan’ aos 123 4 6 170 2 4 © © w . 2,3 4 5 6€ Alb 6 20 4 Slp==, [oT2T4ToJele]) 3]0 © 0 -4 -2 w 4 [ao © © 0 w 8 5|[r7 wow 4 6 6]0 ~ wo w wo 0 k=2 # 1fo (2) a3] [4] [5] 076] 2}2 i 2 4 o © © 314 1 | 0+2 044 Ota Ota Oto _ 2 | 240 23 241 245 2to slo 3 |4to 440 44 4.2 4t0 6]a 4 [ota oto wt0 oto ot8 5 wto oto wt4 wt) mwt6 6 lee ee es ety et min= 2 =I 0 2 @ When k =3 [2] [3] [4] [5] [6] i 2 “1 0 2 ~o 1fo 1 | 0+2 0+4 OF OF O+o 2]2 2 | 240 23° 241 245 2+o 3 ]-1 3 |-lto -140 -I-4 -1-2 -I+a@ 4}o 4 | 0+ Oto 0+0 OF OF8 5} 5 2+ao 2+o 244 2+0 246 6]a 6 [ato wtw wta ota oto Ls by lL bet Le mn= 2 - 5 3 8 When k = 4 d‘(2] : d‘[3] d‘[4] d*[5] [6] i 2 -1 5 3. 8 1 [To 1 012 014 Otwm Oto Otw 2 142 2 2+0 2-3 2+l 245 2+ S11 3 -lto -140 1-4 -1-20 -lt+00 4|-s 4 | -5Sto -Sto -5St0 -Sto -5+8 5 |] 3 5 3to -3+00 -3+4 -34+0 -3+6 clk sles rs hs ts & min= 2 “1 - : Sunstar Exam Scanner 23 IV Sem (CSE / ISE) Devigr and Analy b Ans, 2) A 3] a4] a5) 6] ~ i | 3 3 t 1] 042 0M Ot Oo Oto 2 2] 240 23 21 245 ate 3 Bf eteo 140 142 then ads 4 | Sto Sta 540 Sta 548 $ S| 3m 3m 384 340 346 Stes Lite bs be be min= 2 -l oy 3 So, the final distance matrix obtained for each k=23,4,5is 234 5 204 ww 2-1 0 2 | Initial 0 0 OR 2-1 Seng 0 0 d fork=2 d fork=3 fork=4 fork=5 Shortest path from Ltol= 2-1-5 3 3 +l 5 3 wwe 8 Sa 1to6=3 Write a note on travelling sales Person problem, (05 Maris) Given n cities a Salesperson starts at a specified city, visit all ne} Cities only. Once ity from where he has started, To solve TSP using dynamic Programming consider a 8raph G = where V is Set of vertices and Eis set of edge. Various points to temember are 4. The tour ‘may start from any edge (I,k) where k=. {L} A There is a path from vertex k to |, The path from Vertex k to vertex | goes through cach vertex V.. {1 IH. Let a.) be the cost of 4 shortest path start i going through all Vertes ingar terminating apse ; Path starting at vertex j going through The function (1, V-(1 Th })is the least cost of an optimal sales person tour from the Principle of Optimality, Sunstar Exam Sram a x05” Model Question Paper - 1 forvertex| (VU) =52P (Ca e(kav-tux)} v, The above relation can be generalized as . min Fe a(iS)= jes“ +2()S~(j})} Where [S|cn-1 i#1 AS tes vi. The basecaseis given by the g(in6)=C, for lsisn and i#1 when [s|=0 ¢. Write optimal binary search tree algorithm, analyze the efficiency. (05 Marks) Ans. Algorithm Optimal BST (P[I_.n]) ‘input : an array P[I..n] of search probabilities for a sorted list of n keys output : Average number of comparisons in succeful searches. for ie 1 tondo cfi,i-l] -—0 c[i,i] — PLi] Riki] 1,c43,d>4 Cost = 2+6+1+4 IV Seen (CSE / ISE) Devignand Analyiy Alert, b. Write short notes on following. i. Graph coloring ii, Hamiltonian cea ; . et sum problem ' _ (2 Ans, ee ig : Let g be a graph and m be a given positive integer, Went discover whether the nodes of G can be colored in such a way that no two a ch th nodes have the same color only m color are used. Note if de’s the degree of the Bi m graph then it can be colored with d to | colors. ve The m-colorability optimization problem asks for the smallest c can be color integer is referred to as the choomatic number of graph. (b) ' @-/-O 3 Above graph can be odored with colors 1,2,3 the color of each node is indicated to it. It can also seen three colores are needed to color the gaph, hence this graph chomatic number is 3. A graph is said to be planar if it can be drawn in a plane in such a way that no two, edges cross each other suppose we represent a graph by its adjaency matrix G[I:n,, | ; n} Where G[i,j]=1 if (i,j) is an edge of G G[ij]=0 otherwise. The colors are represented by integer 1,2...m and the solutions are given by the n= tuple (x,,x,...x,) where x, is teh colore of nore i state space tree of degree m and light n+1, Each node at level i has in children corresponding to the m possible assignments to x, 1Si — ccs - Model Question Paper - 1 Sw ‘=o Mcoloreffi Next valueefficiency=O(mn) el . Totalefficiency = }°m'"' n= Ymn= O(m*n) ‘0 ‘at ji, Hamiltonian Cycles : Let G=(V.E) be a connected graph with n vertics, Ahamiltonian cycle is a round trip path along n edges of G that visits every vertex once and return to its starting position the graph G1. Qo @) So ©—®) Contains the Hamiltonian cycle 1,2,8,7,6,5,4,3,1 Graph G, has no Hamiltonian cycle. Backtracking algorithm that finds all the Hamiltonian cycle in a graphs. The graph may be directed or undirected only distinct cycles are outputs. The backtracking solution vector (x, - x,) is defined so that x, represents the i,, visited vertex of the proposed cycle. Next value function which determines a possible next vertex for the proposed cycle. ALGORITHM Nextvalue (k) { repeat x(k] = (x{k] + 1). mod (n#1) if [x[k] = 0] then return; if G[x[k-1] , x[k] = 0) then forj=1tok-Ido if (x[j] = x{K) then break; if G=K) then if (k0 impliesthatf(n) hassameorderof growth g(n) = B(n) co implies that f (n) has larger order of growth then g(n) Since imitisconsiant both hassameorder of growth wl 5n(n~1)€@(n*) (in!=en(2") ffa)=nt—_g(n)=2 al 2nn( 2) a lim — = jin L-_*~-- = fir — tin >> = lin in a) Suicar Exam Scanner / 35. Design and Analysis of Ai IV Sem (CSE / ISE) 2a Ans, 36 a2) Since f (n) has larger growth than g(n) snleQ(2") OR (10 Ma, ot Stem Explain aigorithm specification and analysis framework. : In computational theory, an algorithm and a program are distinguish from each Algorithm has to satisfy finiteness. Where program some program run till sy, crash (Ex - Operating system) We can describe algorithm in many ways 1, Natural language (English) 2. Graphical representation (flow charts) 3. Pseudo code (resembles C) Pseudo code use following to define algorithm 1, Comment begin with and continue utilend of line 2. Blocks indicated with marching { & } braces. : 3. An identifier begins witha letter the data type of variable are not explicitly declared 4, Assignment of value is done wing assignment statement. 5. There are two boolean values true and false, & three logical operator and or and not & the relational operator <<=> >= & = is provided 6. Elements of multidimensional arrays are accessed using [&] Ex A [i,j] 7. The following loop statements are empjoyed : for, while repeat until. while do { } : for variable:: = value | to value 2 step step do { statement | } until 0 8. A condition statement Las following forms if then if then else repeat case { : : : : : else Sanstar Exam Scanner + MOGeY RUEMOW Paber ..2 } Beery Algorithm sel gorithm selection sort ten) sort the al. ( farks= Tondo SMPAS2Enng ore { isi; for k:=i+ | ton do t=afi); afi] : = afj]; aj) =t; } } Analysis frame work There are different method to solve sin, le problem it ir i method that can apply to solve the proble ae oo "there are two kinds of efficiency: (1) Time efficiency (2) Space efficiency Time efficiency : Indicates how fast an algorithm nuns Space efficiency : deals with the extra space the algorithm requires, Now the amount of: extra space required by an algorithm is typically not of as much concern but time is still important to measure efficiency of an algorithm. ‘Program space (Space to store program) Component that effect space —> |-» Data space (Space'to data store) ‘Stack space (To data store) (tap data local variable) ‘Speed of the computer Choice of the programming language Component that effect time efficiency > |-> Compiler used Choice of the algorithm : Number of Input/Output We do not have any control over speed of computer programming language and compiler. " only (1) Choice of algorithm (2) Number of input and output ; Measuring input size — almost all algorithms run longer on larger ieee ; Ex. Sort larger arrays. therefor it is logical to investigate an algorithm is ef re 8 a function of some parameter n indicating the algorithm s input size * fin) a are situations, where the choice of a parameter indicating an input size does mi : : 37 —-Satttar Exam Scanner IV Sem (CSE / ISE) Ans, 38 os Desigrvand Analysis oF Algorithy, -s the choice of an approp1 Size eg ex compute multi natrice h be influenced by operations of the algorithm in question. ex: input size of spell checking algorithm. ; | : We can make a special note about measuring the size of inputs for Algorithin, involving properties of number ex: checking n is prime or not . ' for such algorithms, computer scientists prefer measuring size by the no b in bite ing n’s binary representation. . b=[log,n] tl Explain worst case, best case and average case efficiency with a ‘pei 2am pl . Ma An algorithms efficiency as a function of a parameter indicating the size ore algorithm input. But there are many algorithm for which running time depends ot only the size of input but also on the specifies of a perticular input. Example : Sequential search ALGORITHM sequential search (A[0...n-1], k) /input ; An array A [0..n-1] // output : The index of the first element of A that matches k, ied whilei2Ccan be: Computed using matrix. Multiplication and addition of operation “pplication tomatrices of size4 x14 Sincetwo? x 2 matrices can beaddedintimecn? forsameconstantc, 2 theoverall T(n) Suter Exam Scanner 39 ae IV Sem (cst / 158) 40 — Derignand Analysis of a _’ nns2 T(r) eso n>2 Where bécareconstant : We can attempts to reformulate the equation for Ci So as have fewer my. m iti et . Fak ae @ only 7 multiplication and 18 addition or subtractions by Wig Volker strassen method. Method first computing seven n/2 x Computed using the formulas. P=(A,,+A)(B,, +Ba) Q=(Ay+An)B, R=A,(B,~B,) S=A2(B,-A,) T=A3(B,-A,) 21~A,,)(B, +B.) V=(A,-An)(By +By) C,, =P+S-T+U C,=R+T Cy =Q4S Cy =P+R-Q+V Them resultime recurrence relation b ns2 T(r) =brgg a n>2 seat(a}oar' [ie 4%) +()"] +(i)7 =ALi) doj —j-1_ while (key < ALD if(i 1. Since the recursive calls end whe! then, the initial condition is A(1) = 0. So let us apply this recipe to our recurrence, which for n = A(24) = A(21) + I fork > 0, A(20) = 0. Now backward substitutions encounter no problems: A(2*) =A(2*-1) + | substitute A2-1) = AQ‘-2) + | [A(2*2) + 1]+ 1= A(2-2) + 2 substitute A(2*-2) = A(2*-3) + | = [A(2*3) + 1]+ 2=A(2*-3) +3 =A(2-i) +i = A(2'-k) +k. Thus, we end up with A(24) =AC) +k =k, of, after returning to the original variable n = 2k and hence k = log, n, A(n) = log2 n € Theta(log n). nn is equal to I and there are no additions m 2* takes the form OR Explain the binary search algorithm in detail, with an example. Show that wo" case efficiency of binary search is in 0(log n). 10 Mart a sorted array Binary search is a remarkably efficient algorithm for searching in ‘Sunstar Exam 5 to aif ft Binaryseuch (A, 7 = Ko amy A i) 2 es wan index OF the ATAY’selerneny = jo nl egy joo 40 Alto wile feed mee 12) mam] return m y binary search wee aie k= a ae 3 7 an 27,65 “ 5.99 " SEICLIC itration 1 loom iteration 2 lt r iteration 3 ni Jo analyze efficiency of binary: search is pre ieee with an element of array, © count the Punk o in ie) : “ snl) 4 forn>..(I) (0) 2 be call" nel (fede te ogant tml?) “ lle] 1=[log, (n+l veg Colt)? )={log,n] +1 in equation 1) poiveeven number if n ispositiveandeven eli seri 0LHS of equation forn =2i Coa(0)=[log,n ]+1=[ log,2i]+1 ={log,2 + log,i J+ 1 =(1+[log,i|)+1=[ log, i]+2 nso tcf) Stes, ora (i) + 1 e cal sorting with an example, vatedly., identify in a remainin di edges and delete it along wit a outgoing from it, The order in which the vertices are deteted yielg : wade ; i topological sorting problem. my Example : © (,) ood delete C,, which is source (No incoming edge), delet all Outgoing edge b. Explain source removal topologi Ans. In source removal technique 5 repe: which is a vertex with no incoming Step 1: oh Step 2 : delete C, and all outgoing edge from C, . Step 3 : delete C, and all outgoing edges from Gc, © Step 4: delete C, and all outgoing edges Step 5 : delete C, Step 6 : the solution obtained is C,C,CyC,C, Note that solution may different from the one obtained by DFS. Sunstar Exae su conquer technique. Write a recy, : spe 4 gm element from alist is ae a way ided into several subproblems of the s, ast fF -oplem AM Ived (typical i 1.) sige. re solved (typically recursively, th si ms . '; ougl ast gut! Ay ed, especially when subproblems bean mete "dite 2M ise solutions to the subproblems are combined cae it Solution to the ive algorithm for find ng Marky ideally of abe ? ame type, SS pa ri imaum(int array(), int index, intlen) ininde™ olen?) { jndex] > array[index + 1]) itorayl return array[index]; a return array[index + 1]; a maximum(array, index + I, len); mx dex] > max) iar array[index]; else . return max; oth minimum(int array], int index, intlen) | index? len-2) iffarray[index] < array[index + 1]) | return array[index]; else return array[index + 1]; } min = minimum(array, index + |, len); iflarray[index] < min) return array[index]; else return min; } . MODULE -3 . a ti the general method of greedy technique. Briefly describe i Maris) rks in stages Al M8. The greedy method suggests that one can device an algorithm that wo! Sauter Exam Scanner 45 rT, IV Sem (CSE / ISE) Design and Analyste of A i i ision is made regarding w tee input at a time. At each stage, a decision is made reg 8 Whet, i pane ena optimal solution. This is done by considering the inp the order determined by some selection procedure the function select selects an Pa from af } and removes it ALGORITHM Greedy (a,n) /Hinput : An array of n element { Solution = fori: = 1 ton do { X: Select (a); if feasible (Solution, x) then solution - Union (solution,x); } return solution } Coin change problem: A child buys candy and gives a$1 bil tthe chashien. The cashier wishes to return change using the fewest number of coins, Assume that an unlimited supply of quarters, dimes, nickles and pennies is available. The cashier constructs the change in stages, In stage a coin is added to the change this coin is selected using the greedy technique, At each stage increase the total amount of change constructed by a much as Possible, To ensure feasibility of a solution, the selected coin should not ensure the tota] amount of change given so far to exceed the final desired amount. b. Explain transform and conquer technique. Design and analyze heap sort algorithm with an example, (10 Marks) Aus. Group of design methods that are based on idea of transformation is called as 46 transform and Conquer. These methods works as 2 Stage procedure, Instance simplification, © Transformation to a different representation of the same instance - Representation change, . Transformation to an instance of a different problem for which an algorithm is already available - Problem reduction, . Problem’s instance ~ Simple instance Solution Heapsort — This is a ‘Wo stage algorithm that works as follows : Stage | : Construct heap for a given array, Stage 2: Apply the root deletion operation n- I times to the remaining heap. Sunstar Exam Scanner ALGORITHM Heapbottom for i [1/2] down to | do keiv Hk) heap < False wee not heap and 2 * k < me ifj Hj] heap — four else H[k] — H[j]; k j Hk] —v HCL ap mum key deletion from a heap we Exchange the root’s key with the last ke P ease the Heap’s size by |. 2: Dect yi : Heapify the smaller treé by shifting k dows Soto - up heap construction. the tree exactly inthe some way Y k of the heap, Efficiency * Construction stage of algorithm is in O(n). second stage, time efficiency is compute by number . eliminating the root keys from the heaps of diminishing oe Key comparison (a), from n to 2 Cn) 2[log, (n- 1) }+2[log, (n-2)]+...4 2ogp1s 25 og, ay log, (n-1) ry =2(n-1)log, (n-1)<2nlog,n Thismeans that C(n) €O(n log n) for thesecond stageof heapsort. Soefficiency=O(n) + O(n logn) =O(nlogn) Worst case and average caseC(n) = 6(nlogn) Example : Sorting the array 2,9,7,6,5,8 by heapsort Stage I (heap construction) Stage 2(maximum deletions) 29 76 5 8|9 6 8 257 29 8 6 5 7/7 6 8 2 $ \9 29 § 6 5 7;8 6 7? % 92 8 6 5 7{5 6 7 ? i 47 rar Exam Scanner IV Sem (cst / ISE) Devigrv andl Anclyis al S652 5 7/2 6 2 2 S 76 5 ft 6 2 3 Soc See 2. |s 2 6. a. Write Kruskal’s algorithm to construct a mini it e imum spnning tree. Apply algorithm and construct to spanning tree for given graph. te (08 ars Ans. : 48 Sunstar Exam Scanner ee r 5 - Model Question Paper - 2 cB ALGORITHM Kruskal (G) E,— Q5 encounter “0 ke0 while encounter < kek+] ifE, Ufe return E. M-1 do a} § counter « ecounter + i be of ab bf cf af df ae cd de 12344556 68 be of ab bf cf af dfae cd de 12344556 68 & 49 Sutstar Exam Scanner a —_penignanh Analyse of aig. 50 & IV sem (CSE ( ISE) fal be of ab bf & 123445 2 be of ab bf cfafdfae cd a 12344556 fhm will be in OE! log |EI) hm. Apply Dijkstra’s algorithm - (08 at Efficiency of kruskal’s algorit b. Write Dijkstra’s shortest path algorit! eee obtain shortest paths assuming vertex : ALGORITHM Dijstra (G,s) for every vertex v in V do d/—0;P —null insert (Qv,d)) 4, — 0; Decrease (Q.s,d,) *-0 for i — 0to|V|- Ido U* — DeleteMin (Q) Vie V, U{u%} for every vertex uin V-V_ that i f fa t ifd*, + W(W(u*,u) < om dae d,*+w(u*,u): Pout Decrease (Qwd) " s adjacent to u* do ” ogcs Model Question paper -2 Tree | Remaining [a[V} = min(d[v}, dul + wlu,v)) vertices vertices find u = d{u) ue V-S 5,3 ee [0] = min(w.4+ a) = 0 d{l] = min(ar4+10) = 14 [2] = min(oot4s ©) = 6% [4] = min(ot4+35)=39 [0] = min(<0,14+ 00) = a [2] = min(co,14+15) = 29 [4] = min(co,14+20) = 34 [0] = min(o,29+20) = 49 [4] = min(34,29+ 0) = 34 [0] = min(49,34+ o)=49 pll]=3 The shortest distance from 5 to 0 is 49, c. Explain the bottom up heap construction algorithm. Give the worst case efficiency of this algorithm. (04 Marks) ‘Ans. Step 0: Initialize the structure with keys in the order given Step 1: Starting with the last (rightmost) parental node, fix the heap rooted at it, if it doesn’t satisfy the heap condition: keep exchanging it with its largest child until the heap condition holds Step 2: Repeat Step | for the preceding parental node het el Coon (M =P) YL 2¢h-i)=5'2(h-1)2! =2(n— log, (n+ ») 120 level keys imo MODULE - 4 7, a. What is dynamic programming? Explain multistage graph with an example. (10 Marks) Ans. Dynamic programming is an algorithm design technique for solving problems with overlapping subproblems. Typically, these subproblems arise from a recurrence relating a solution to a given problem with solution to its smaller subproblems of Sanstar Exam Scanner 51 pesigrv nd Anayrs of ng over!dpping problem again ang, —~ each of the smaller subproblem cain, sone iom which we can then obt fn table from which we c on tal a Solupighee ‘ IV Sem (CSE / ISE) the same type. Rather than solvi programming. Suggests s recording the results in a original problem. Example the Fibonacci problem, 0,1,1,2,3.5,8,13,21..- which can be defined by the simple recurrence F(n) = F(n-1) + F(-2)— forn>2 and F(0)=0 FOU)=1 —_ Nt) We can record Previous two number to compute next number in Series, Multistage graph : Amultistage graph G = isa directed graph in which the vertices a Sk. In addition if < u,v> is an edge in ei part en into k2 2 disjoint sets V,,1s and < V,,, for some i | the cost of path fro: i : iJ m S t the edge on the path 5 OCIS the sum of The multigraph Problem is to find a minimum cost path from S to t. B, ° cl V iar a stage in the graph. Because of the constaint on E, Eve me ieee to stage 2 then stage 3 then stage 4 and so on, ple - 5 stage graph, A minimum cost s to t path is indicat ‘ach TY Path s tot sam in led by broken eg, acs - Model Question Paper ..2 Ans, Consider a resource allocation problem in whi, to r projects. em in which n units resource are to be allocated If units of resource is allocated to-project j ; ir ject i then the resulti is NG The problem is to allocate the resource to ther projects in such i Seaman Stage i 1 Sir represent project ; venices=atl Vj O0Sjen ett Stage | : Source = V(1,0)=s Sink = V(r+1,n)=t ‘A dynamic programming formulation for k stage graph problem is obtained by first noticing that every s to t path isthe result of a sequence of k - 2 decisions the ith decision involve determining which vertex in Vit C,m,0 Each m, must bein range! =lof nodel | ave Ib=19 Xlb>lof nodel | a-pbischosen path Letconsider abe Ib=16 sabod Ib=16 arbre Ib=19 X_ Ib>lofnodel! Hencea> b->c choosen path Letconsider agbocodjesa Ib=24 .. first tour arbrcte sda Ib=19 better tour - avbodtc sea 1=24 .. inferiortour apbodtepcsa 1=16 :.Optimaltour Define deterministic and non-deterministic algorithm. (04 Marks) In deterministic algorithm, for a given particular input, the computer will always produce the same output going through the same states but in case of non-deterministic algorithm, for the same input, the compiler may produce different output in different runs, In fact non-deterministic algorithms can’t solve the problem in polynomial time and can’t determine what is the next step. The non-deterministic algorithms can show different behaviours for the same input on different execution and there is a degree of randomness to it. Ee OR 10. a.Explain 0/1 knapsack problem by (i) C branch and bound solution (ii) FIFO Branch and bound solution. (12 Marks) Ans. LC Branch and Bound solution : LC branch and bound search using "C(1) and u (.) as defined. Sunstar Exam Scanner 61, a egrvana Analyste OF ALGOr thy IV Sem (CSE / ISE) Deg ise u(x)=U Bowe Twix c(x)=Baun{-aZ wri!) rd Example : n= 4,m= 15 (PyPyPyP.) = On os 7 8) (W,,WypWy,) = (24,65 weenie a(t) has values UBound (00015) UBound scans through the obj ting from j. 38 from left to right sta 38 (ii) Using FIFO Branch and Bound solution node | is the E node and the queue of live nodes is empty ode upper is initialized ‘9 uC 1) =-32 Initially the root node, since this is not a solution n 62 Sunstar Exam Sean (08 Marks) WW! »blet os Con eens on 8 x & chess board so that no queens attacks another queen. Pimeenatack another if the two are in same row, column or diagonal A 12345678 ° «¢ Identify data structure to solve the problem ehh since each quen is in different row, define the chess boar solution to be and 8 - tuple. x8) Le vs the column for the quen ¢ Identify explicit constraints ¢ Explicit constraints using 8 tuple formulation are S,=£(1,2,3,4,5,6,7,8) ‘¢ Solution space of 8 x 8 8 tuples ¢ %dentify implicit constraint @ Notwo X, can be sam ¢ All solution are permutations of 8 tuple (152;3:435;6;7;8) Reduce the size of solution space from 8 x 8 to 8! tuples. @ No two queens can be same diagonal. ¢ The solution above is expressed as 8 tuple as X = (4,6,8,2,7,1,3,5) Five walks through the 8 queens problem Sa aan Seannr 63 2 Ans. me: 3 urth Semester B.E. Degree Examination, CBCS - June / July 2017 Design and Analysis of Algorithms s Max. Marks: 80 FIVE full questions, selecting ONE full question from each module. Note: Answer any” Module - 1 », Define algorithm. Explain asymptotic notations, Big O, Big Omega, Big Theta notations. (08 Marks) ‘An algorithm is a procedure or formula for solving a problem, based on conducting a sequence of specified actions. A computer program can be viewed as an elaborate thm. In mathematics and computer science, an algorithm usually means a small jure that solves a recurrent problem, Asymptotic Notations are languages that allow us to analyze an algorithm's cunning time by identifying its behavior as the input size for the algorithm increases. This is also known as an algorithm’s growth rate. Big-O Notation: {A function t (n) is said to be in O(g(n)), denoted t (n) € O(g(n)), if t(n) is bounded above by some constant multiple of g(n) for all large n, i.,, if there exist some positive constant cand some nonnegative integer n, such that t (n) < cg(n) for all n> n,. 2 O-notation ‘A function t (n) is said to be in 2(g(n)), denoted t(n) € Q(g(n)), if t(n) is bounded below by some positive constant multiple of g(n) for all large n, i.e., if there exist some positive constant c and some nonnegative integer n, such that t (n) > cg(n) for all n2 n,. Theta-notation ‘A function t (n) is said to be in Theta (g(n)), denoted t (n) € Theta(g(n)), If t(n) is bounded both above and below by some positive constant multiples of g(n) for all large 1, ie., if there exist some positive constants cl and c2 and some nonnegative integer n, such that c,g(n) n,, Explain general plan of mathematical analysis of non-recursive algorithms with example. (08 Marks) General Plan for Analyzing the Time Efficiency of ‘Non-recursive Algorithms |. Decide on a parameter (or parameters) indicating an input’s size. 2. Identify the algorithm’s basic operation. (As a rule, its located in the innermost loop.) 3. Check whether the number of times the basic operation is executed depends only on the size of an input. If it also depends on some additional property, the worst-case, average-case, and, if necessary, best-case efficiencies have to be investigated separately. 4, Set up a sum expressing the number of times the algorithm's basic operation is executed. 5. Using standard formulas and rules of sum manipulation, either find a closed form formula for the count or, at the very least, establish its order of growth. ALGORITHM MaxElement(A[0..n - 1]) Determines the value of the largest element in a given array Moput: An array A[0..n — 1] of real numbers Output: The value of the largest element in A Sutstar Exam Scanvior 1 and Analyte FAlgor ity, IV Sem (CSE/ISE) Deg 2a Ans. maxval maxval maxvaleAli) return maxval ve size here is the number of elements in the aa a te a ae cai a operations in the Ioop’s body: the comparison ATi maxval ,% loop. There are wo OP], Which of these two “iperations should We consider bast econ virion ia executed on each *epcttion of the 1oop and the assignmen? ae : Maal consider the comparison to be the algorithm's ba: i eee Note iy ror gamber of comparisons will Be the same for all arrays of size Nt erefore, in terms this metric, th ns wpa among the worst average, and Pest ses hey here is no nee cine et : : This is an easy sum to compute Because t is nothing other t Thus, n-1e€ ‘Theta(n). han J repeated n~ 1 time, OR J space complexity. Explain important problem types. (08 Marks) fan algorithm quantifies the amount of time taken by an algorithm tg the length of the input. Similarly, Space complexity of an algoritim f space or memory gorithm to run as a function of Define time and Time complexity 0 runias a function 0 quantifies the amount o} the length of the input. Important Problem types: : a. Sorting b. Searching d. Graph problems c. String processing r ©. Combinatorial problems f, Geometric problems g. Numerical problems a Sorting algorithm is an algorithm that puts elements of a list in a certain order. The sorting ferders are numerical order and lexicographical order. Efficient sorting is important to optimizing the use of other algorithms (such as search and merge algorithms) that require sorted lists to work correctly; it is also often useful for canonicalizing data and for producing human readable output. More formally, the output must satisfy two condi 1. The output is in nondecreasing element according to the desired total order) 2. The output is a permutation, or reordering, of the input. Searching: In computer science, a search algorithm, broadly speaking, is an algorithm for finding an item with specified properties among a collection of items, The items may be stored individually as records in a database; or may be elements of a search spat defined by a mathematical formula or procedure, such as the roots ‘of an equation with integer variables; or a combination of the two, such as the Hamiltonian circuits of @ graph. Searching algorithms are closely related to the concept of dictionaries. String searching algorithms are important in all sorts of applications that we mee day. In text editors, we might want to search through a very large document (say # taken by an all order (each element is no smaller than the previous t every Sunstar Exam Seat’ a pune July) 2037, currence of a given sI (maybe dozens of characters). cet we might potentially want to search through thousands of such in eX ats (though normally these files would be indexed, making this unnecessary). doe! metric algorithms deal with Beometric objects such as points, lines, and polygons: ea Greeks were very much interested in developing procedures for solving 4 Ancien ¢ geometric problems including problems of constructing simple geometric pape tae ems, another | i i rercal prob lems, another large area of applications are problems that involve ical objects of continuous nature: solving equations and system of equation, matting definite integrals, evaluating functions and so on. The majority of such coreratical problems can be solved only approximately. nustrate mathematical analysis of recursive algorithm for tower of Hanoi. - a (08 Marks) The number of disks n is the obvious choice for the input’s size indicator, and so is moving one disk as the algorithm’s basic operation. Clearly, the number of moves M(n) depends on 1 only, and we get the following recurrence equation for it: M(n) = M(n~ 1) + 1+ M(n = 1) for n> 1. with the obvious initial condition M(1) = 1, we have the following recurrence relation for the number of moves M(n): M(n) = 2M(n- 1) +1 forn> 1, M(J)= 1. We solve this recurrence by the same method of backward substitutions: Mia) = 2M(n ~ 1) + I sub. M(n~ 1) = 2M(n~2) +1 [2M(n - 2) + 1]+ 1= 22M(n— 2) +2 + 1 sub. M(n — 2) = 2M(n-3)+1 = 2>(2M(n — 3) + 1]+2 + 1=23M(n~3)+22+2+ 1. The pattern of the first three sums on the left suggests that the next one will be 2‘M(n — 4) + 23 + 22 +2 + 1, and generally, after i substitutions, we get M(n) = 2'M(n-i) +241 + 2-24... +24 1=2M(n-i) +2'- 1. Since the initial condition is specified for n = 1, which is achieved for i= n — 1, we get the following formula for the solution to recurrence Ma) =2n-IM(n—(n~ 1) + 2n-1-1 =2n-1M(1) + 2n-1 ~ 1=2n-1 + 2n-1 - 1=2n-1. Module - 2 3.2. Explain concept of divide and conquer. Write merge sort algorithm. (08 Marks) Aas. Divide-and-conquer algorithms work according to the following general plan: 1.A problem is divided into several sub problems of the same type, ideally of about equal size, 2. The sub problems are solved (typically recursively, though sometimes a different algorithm is employed, especially when sub problems become small enough). 3. If necessary, the solutions to the sub problems are combined to get a solution to the original problem. Setar Beam Seater 3 “= ce IV Sem (CSE/ISE) Design and Analysis F AlgOrithyy, OT —————_*= Cl sae 77 smprotiem 2 ‘onsen? ALGORITHM Mergesort(A[0..n — 1]) W/Sorts array A[0..n — 1] by recursive mergesort /Anput: An array A[0..n — 1] of orderable elements Output: Array A[0..n — 1] sorted in nondecreasing order ifn>1 copy A[0..n/2 — 1] to B[O..n/2 ~ 1] copy A[n/2...n ~ 1] to C[0..n/2 — 1] Mergesort(B[0..1/2 — 1) Mergesort(C{0..n/2 ~ 1]) Merge(B, C, A) ALGORITHM Merge(B[0..p — 1], C{0..q ~ 1], A[0-p +a — 1). 1/Merges two sorted arrays into one sorted array /[nput: Arrays B[0..p — 1] and C[0..q — 1] both sorted 1/Output: Sorted array A[0..p + q— 1] of the elements of B and C i +0; | —0; k—0 while i

I, ACO” she recursive calls end when n is equal t a sie Condition is A(1) =0. SAuAl 10 1 and there are no additions made then, he" ly this recipe to our Tecurrence, whi - s e oe 1) + Lfork>0, ich for n= 2* takes the form AC <0. 20 substitutions encounter no Problems: Ney) ACH) +I substitute A(21) = A242) + | agi) + Ut 1 AQH2) +2 substitute A(2) = AHI) +1 Waes)+ I} 2=AQ43) +3, “sagt ti “eat tk us, we end up with : A2)=A(1) + k= k, oF, after returning to the original variable n= 2* and hence k = log, n, A(n) = log, n € Theta(log n), OR IMustrate the tracing of quick sort algorithm for the following set of numbers: 4* 55,10, 72,18, 40, 11, 64, 58, 32, 9 (08 Marks) - 2% 10 72 18 40 11 64 58 32 9 2 10 72 18 40 1 64 58 32 9 2% 10 9 18 40 1 64 58 32 72 2 10 9 18 1 40 64 58 32 72 10 9 18 25 40 64 58 32 72 9 10 WM 18 25 40 32 58 64 72 32 40 S58 64 «(72 b. List out the advantages and disadvantages of divide and conquer methods and illustrate the topological sorting for the following graph. (08 Marks) co Sem (CSE/ISE) Design and Analysts of AL EX ay) : : “a: NEX i all £ 7 delete C2 @

You might also like