0% found this document useful (0 votes)
538 views27 pages

MCS 211 2023 1

Uploaded by

ladokod693
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)
538 views27 pages

MCS 211 2023 1

Uploaded by

ladokod693
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/ 27
‘et ozs ys Tony Sty HELPER wow lenousite.com = SUNIL POONA Course Code : MCS-211 Course Title : Design and Analysis of Algorithm Assignment Number : MCA(1)/212/Assign/2023 ‘Maximum Marks : 100 fe = ea Weightage :30% www.ignousite.com Last date of Submission : 30" April, 2023 (for January sess 131" October, 2023 (for July session) QA. a) Develop an efficient algorithm to find alist of all the prime numbers up to a number n (say 100). ‘Ans, One efficient algorithm to find all prime numbers up to a given number n isthe Sieve of Eratosthenes algorithm. This algorithm works by iteratively marking the multiples of each prime number as composite, and then moving on to the next unmarked number until all numbers up to n have been processed. Here's how you can implement the Sieve of Eratosthenes algorithm to find all prime numbers Up to 100: Create a list of all numbers from 2 to n. Start with the first ptime number, 2, and mark all of its multiples as composite by setting their corresponding values in the list to 0. 3. Move on to the next unmarked number (in this case, 3) and repeat the process, marking all ofits multiples as composite. 4, Continue in this manner, moving on to the next unmarked number and marking its multiples as composite until you reach the square root of n (rounded up to the nearest integer). All unmarked numbers in the list up to n are prime numnbers. Here's the Python code to implement this algorithm: def find_primes(n): A create a list of all numbers from2 ton list{range(2, n+1)) ff [terate over all numbers up to the square root of n for jin range(2, int(n**0.5}+1): if numbers{i-2] !=0: # mark all multiples of i as composite for jin range(i**2, n#4, i) numbers|j-2] = 0 ‘tall unmarked numbers are prime for num in numbers: st00r, if num =P nn EY won NY You can test tis function by calling nd_primes{00), which wl return the ist [2, 3,5, 7, 11,3, 17,19, 23,28, 31,37, 4,43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] 'b) Explain the following types of problems in Computer Science with the help of an example problem for each: i) Searching Ignou Study Helper-Sunil Poonia Page 1 ft Toulon Sry Heeee www ignousite.com ey SUNIL POONIA ‘Ans. Searching problems in computer science involve finding a specific item or value in'@ Gata structure. This can include searching for an element in an array, a key in a dictionary, or a node in a graph. The goal isto efficiently locate the item you're looking for and return it, fit exists. Example: Let's consider an example problem of searching for a specific element in an array of integers. Suppose we have an array of n integers and we want to check if a given element x is present in the array. One approach to solving this problem is the linear search algorithm, which involves iterating over the array one element at a time until the element is found or the end of the array is reach. ‘ey i eo i) String Processing \ ‘Ans. String processing is an important area of computer science that deals with the manipulation of strings, which are sequences of characters. There are various string processing problems in computer science, and they can be eategorized based on the type of operation or task that needs to be performed on the strings, Example: One example problemin string processing is the "Longest Common Subsequence” problem. Given two strings s1 and 2, the problem is to find the longest subsequence that is common to both s1 and §2. A subsequenceiis a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. iii) Geometric Problems ‘Ans. Geometric problems are problems in computer science that involve geometry, such as finding the intersection of two lines or the closest pair of points in a set. These problems can be solved using various algorithms and data structures, and they have ‘many practical applications in fields such as computer graphics, robotics, and geographic information systems. Example: One example of a geometric problem in computer science is the problem of finding the convex hull of 2 set of points in the plane. The convex hull is the smallest convex polygon that contains all of the points in the set. This problem has many practical applications, such as in computer graphics, where itis used to draw the outline of a shape, and in robotics, where itis used to plan the movement of a rebot in a 20 environment, iv) Numerical Problems ‘Ans. Numerical problems in computer science refer to computational problems that involve numerical calculations or operations, These problems can arise in various domains such as scientific simulations, data analysis, cryptography, and financial modeling. Example: One example Gfa numerical problem ifcomputer sciénce is the calculation of the value of Pi using the Monte Carlo method. Piis a mathematical constant that represents the ratio'of the circumference of a circle to its diameter, and its value is, ‘approximately 3.14159, The Monte Carlo method is a statistical technique that uses random sampling to estimate the value of a parameter or solve a problem. 19> ute testi ben igen emi Ine erst Porary n(n) (2ne2) Goa: a ed Ans, To prove this statement using induction, we will need to show that it holds true for the base case of n= that if it holds true for n =k, it also holds true forn=k +1. and then show Base case (n= 1): If we substitute n into the formula on the right-hand side of the equation, we get: ALA) 2(0)+2)/6 = 112)(3)/ Ignou Study Helper-Sunil Poonia Page 2 ft Toulon Sry Heeee www ignousite.com = SUNIL POONIA If we substitute n =1 into the left-hand side of the equation, we get: 1221 ‘Therefore, both sides of the equation evaluate to 1 when n= 1, and the base case is true. Inductive step (n= k + 1): ‘Assuming the formula holds true for n = k, we will now show that it also holds true fora =k+1, First, we can rewrite the formula for n = kas: Ve det R= Kk#D)(2KE1)/6 ‘Next, we can substitute ke for min the original formula: P+ De E+ (ken = (hed Re1) 1) 2k /6 Simplifying the right-hand side: (eea)(k+2) 2436 Expanding the left-hand side: K{k+2)(2k+1)/6 + (K+)? Substituting the formula for nek in the first term: (esa) 24/6 + 1/2) + (ke)? simplifying: (ee a)f(2ke 24/6 + 1/2) + (ke) (k+I)[(2k + 7k + 6/6) et (k+1)(k+2)(2k+3)/6 Therefore, we have shown that if the formula holds true for n =k, then it also holds true for n, the formula is true for all positive integers n. +1, By the principle of mathematical induc 'b) What is the purpose of asymptotic analysis? What are the drawbacks of asymptotic aialysis? Explain the Big-O notation with the help of an example. ‘Ans, Purpose of asymptotic analysis: The purpose of asymptotic analysis in computer science fs to analyze the performance of algorithms and data structures as the input size grows towards infinity it helps us to understand how an algorithm or a data structure will perform as the problem size increases, without needing to examine specific input sizes. Asymptotic analysis provides a high-level view of the efficiency of an algorithm or data structure by examining how the runtime ‘or memory usage scales with respect to the input size. This analysis can be used to compare different algorithms or data structures and to select the one that is the most efficient for a given problem. Ignou Study Helper-Sunil Poonia Page 3 test Tony Troy Heeee www ignousite.com — SUNIL POONIA The most common measures used in asymptotic analysis are time complexity and space complexity. Time complexity measures how the runtime of an algorithm or operation scales with respect to the input size, while space complexity measures how the memory usage scales with respect to the input size. Drawbacks of asymptotic analysis: Asymptotic analysis is a powerful tool for analyzing the performance of algorithms and dats structures, but there are some crawbacks to this technique: 11. It doesnot consider the constant factors: Asymptotic analysis only considers the erowth rate of the algorithm or data structure and does not take into account the constant factofs. In some cases, the constant factors can have a significant impact on the actual running time of the algorithm, which may not be captured by the asymptotic analysis, 2. It may not reflect the practical performance: Asymptotit analysis is based on the assumption that the input size is large enough to make the leading term of the complexity dominate the other terms. However in practice, the input size may not be large enough to achieve this condition, which means that the asymptotic analysis may not accurately reflect the actual performance of the algorithm or data structure. 3. Itassumes worst-case scenario: Asymptotic analysis usually assumes the worst-case scenario when analyzing the performance of an algorithm or data structure. However, in practice, the input may not always be in the worst-case scenario, whhich means that the actual performance may be better than what is predicted by the asymptotic analysis. 4, Itmay not account for special cases: Asymptotic analysis assumes that the input is uniformly distributed, and it does not account for special cases where the input is not uniformly distributed. For example, if an algorithm performs well on most inputs but has poor performance on a few special cases, this may not be captured by the asymptotic analysis. Big-O notation: Big-O notation is a mathematical notation used to describe the upper bound of the growth rate of 8 function or algorithm. itis commonly used in computer science to describe the time or space complexity of algorithms. The notation is written as Olg(n)), where g(n) isa function that describes the upper bound of the growth rate of another function f(n) 25 n approaches infinity. In other wards, O(g(n)) represents the set of functions that grow no faster than e(n) asymptotically Example: For example, let's say we have an algorithm that sorts an array of n elements using bubble sort. The worst-case time complexity of bubble sort is O(n"), which means that the running time of the algorithm will not exceed c * n? for some constant c and for large enoughin: To understand this, we can plot the growth Fate of the bulbble sort algorithm against the’growth rate of the function f(n) = n?. As ‘gets larger and larger, the growth rate of bubble sort approaches that of fn) =n”, but it never exceeds it, This is why we say that the time complexity of bubble sort is O(f*). In practical terms, this means that as the size of the array to be sorted grows, the running time of the bubble sort algorithm will increase at most quadratically, Italso means that if we compare bubble sort to other sorting algorithms with different time complexities, we can use Big-O notation to determine which algorithm is most efficient fora given problem. 3. a) Evaluate the polynomial p(x}= 5x°+4x!-3x°-2x"+9xe11 at X=3 using Horner's rule. Analyze the computation using Horner's rule against the Brute farce method of palytamial evaluation. ‘Ans. To evaluate the polynomial p(x) = 5x°+4x‘-3x’-2x'49xt11 at x=3 using Horner's rule, we will follow these steps: Step 1: Write the polynomial in Horner's form, which is: fet 5 2 Step 2: Starting from the rightmost coefficient, 11, multiply it By the value of x, which is 3. Add the next coefficient, 9, to the result. This gives: pl (Sx-+4)x2-3x¢-2)e+9411/1 Ignou Study Helper-Sunil Poonia Page 4 ft Toulon Sry Heeee www ignousite.com = SUNIL POONIA pi3)= 11 (3) =11/1 +8 p(3)=20 Step 3: Multiply the result from step 2 by the value of x, which is 3. Add the next coefficient, -2, to the result. This gives: (3) =20 p03 2 + (203) p(3) =58 Step 4: Multiply the result from step 3 by the value of x, which is 3. Add the next coefficient, -3, to the result. This gives: {3} = 5B p(3) =-3 + (58 x 3) p[3) = 169 Step 5: Multiply the result from step 4 by the value of x, which is 3. Add the next coefficient, 4, to the result. This gives: (3) = 169 p(3) = 4 + (2693) p(3) = 522 ‘Step 6: Multiply the result from step 5 by the value of x, which is 3. Add the next coefficient, 5, to the result. This gives: pI3) = 511 p(3) =5 + (511 x3) p(3) = 1548 Therefore, (3) =1548 whien evaluated using Horner's tule. sry if ‘Now let's analyze the computation using Horner's rule against the brute force method of polynomial evaluation. The brute force method of polynomial evaluation involves directly computing each term of the polynomial and summing them together. For example, to evaluate (3) using brute force, we would compute: (3) = 5(3°) #434) -3(3%) -2(3°) + 9(3) #41 p(3)= 1215 +324-81-18+27+11 (3) = 1458 Comparing the two methods, we can see that Horner's rule requires fewer multiplications and additions than the brute force method. Specifically, Horner's rule requires 5 multiplications and 5 additions, while the brute force method requires 6 multiplications and § additions. Therefore, Horner's rule is generally more efficient for polynomial evaluation, especially for polynomials with high degree. b) Write the linear search algorithm and discuss its best case, worst case and average case time complexity, Show the best case, worst case and the average case of linear search in the following data: 13, 15, 2, 6, 14, 10,8, 7, 3,5, 19,4, 17. ‘Ans. Linear search algorithm: Linear search is 2 simple algorithm for finding a particular value in an array or list. The algorithm, works by sequentially checking each element of the array until a match is found or the end of the array is reached, Here is the linear search algorithm: linear_search(A, x): for tin rangotlen(Al): if Ali] == x: return i return -1 Ignou Study Helper-Sunil Poonia Page 5S test Tony Troy Heeee www ignousite.com cle) SUNIL POONIA The linear_search function takes an array A and a value x as inputs. It then iterates through the elements of the array A one by cone and checks if each element is equal to the value x. Ifa match is found, the index of the matching element is returned. If no ‘match is found, the function returns -1. The time complexity of linear search depends on the length of the array and the position of the target value. Here are the best case, worst case, and average case time complexities of linear search ‘© Best case: The best case occurs when the target value is found at the first position of the array. In this case, the algorithm. only needs to check one element, and the time complexity is O(1). ‘+ Worst case: The worst case occurs when the target value is notin the array or is atthe last position of the array. In this case, the algorithm needs to check everyelement of the array, and the time complexity is O(n), where mis the length of the array. ‘+ Average case: The average case occurs when the target value is randomly distributed in the array. In this case, the algorithm needs to check, an average, half of the elements of the array. Therefore, the average case time complenity is O(n/2), which simplifies to O(n) Let's now apply linear search to the following data: 13, 15, 2,6, 14, 10,8, 7,3, 5, 19, 4, 17 ‘© Best case: itwe search tor the value 13, which is the tirst eleméhit ot the array, the algorithm will only need to check one element, and the time complexity will be O(1). + Worst case: If we search for the value 20, which is not in the array, the algorithm will need to check every element of the array, and the time complexity will be O(13), where 3 is the length of the array. © Average case: if we search for a randomly distributed value, such as 7, the algorithm will need to check, on average, half of the elements of the array, which is 6.5. Since the array has an odd number of elements, we can round up to 7. Therefore, the average case time complexity will be O(7).. Q4. a) Find an optimal solution for the knapsack instance n=7 and maximum capacity (W) =15, {P1,p2,..,P6)=(4,5,10,7,6,8,9) (WI, W2, or WOY=(1,2,3,6,2,4,5) ‘Ans, To solve this knapsack instance, we can use dynamic programming with a table of size (n+1) x (Ws). Thé Entry in cell (i) OF the table will contain the maximum value that can be obtained using items 1.to i, with atmaximum capacity of j The recurrence relation for filling in the table is: © if} = left: mid = left + (right - left) //2 # ifthe element is present at the middle if arr{mid] == x: return mid # ifthe element is smaller than mid, then it can only be present in the left subarray elif arrtmid] > x: return binarySearch(arr, left, mid -1, x) # Else the element can only be present in the right subarray else: return binarySearch(arr, mid + 1, right, x) Ignou Study Helper-Sunil Poonia Page 8 ‘et o's Touov Stvvy HeLpen www ignousite.com = SUNIL POONIA else: 1 Element isnot present in the array return -1 Program: Recursive binary search to find an element in a sorted array of 7 elements: include int binarySearch(int arr], int left, int right, int target) ( if (left <= right) { int mid = left + (right - left} /2; if (arr{mid] return mid; 2. Sof else if (arr[mid] > target) { } else { } t target) { -1, target); return -1; // target not found } int main() { int are{] = (1, 2, 3, 4,5, 6, 7); Int target = 5; Int n = sizeof(arr) / sizeof(arrl0}); int result = binarySearch(atr, 0, n-1, target); if (result ==-1){ printf("Element not found in array" t else { print{("Element found at index Sd", result}; } i rey Output: Hf Element found at index" bb) Analyze the Quick sort algorithm using Master Method. Also draw the relevant recursion tree. Ignou Study Helper-Sunil Poonia Page 9 test Tony Troy Heeee www ignousite.com a SUNIL POONIA ‘Ans. Quick sort algorithm using Master Method: Quick Sort is a widely used sorting algorithm that has an average case time complexity of O(n log n), making it very efficient for large datasets. The Master Method can be used to analyze the time complexity of Quick Sort The Master Method states that if a recurrence relation of the form T(n) = aT(n/o) + fin}, where a >= 1 and b> 1 are constants and f(n) isa polynomial function, then: If (0) = O(n%(log_b a - e]], where e > 0 isa constant, then T(n) = Q(n%(log_b a)) if (9) = ©{n>(log_b a), then T(n) = O(n*(log_b a) log n)- © If f{n) =(n%{log_b a + e)), where © > Oisa constant, and if a * f{n/b) <= * f(q) for some constant c< 2 and all sufficiently large n, then T(n} = (f(n)), For Quick Sort, we have: *a=2, since we aré dividing the input into two parts © b=2, since we are dividing the input in half © f[n) = O(n), since the partition step takes linear time Using the Master Method, we can see that QuickSort has a time complexity of O(n log n). Specifically, we can$ee that log ba= log_2 2 = 1, and f{n} = O(n"), 30 Tin) = 9(n log ni), Recursion tree: Here is a visualization of the recursion tree for Quick Sort when sorting an array of size 8: 13,1,7,5,2,8,4, 6] a \ 112,435,678) () / Ny | (123,4) (56,78) [] IN y 2] 431 15,61 (7,81 te ey NON gy 1. ren (1) (2) (3) (4) hte) (i (8) es of Each node in the tree represents a recursive Call to Quick Sort, and the fiumbérs in brackets represent the subarray being sorted. The tree has a depth of log_2 8 = 3, and at each level the size of the subarrays being sorted is n/2*%. The total number of nodes Inthe tree is 290 + 291 +242 +... +2%d = 2”(de1) -1, where d is the depth of the tree, Therefore, the time complexity of Quick Sort can be expressed as O{n log n), where n is the size of the input array. ©) Write the algorithm for the divide and conquer strategy for Matrix multiplication. Also, analyze this algorithm. ‘Ans, Divide and conquer strategy for Matrix multiplication: The divide and conquer strategy for Matrix multiplication is an efficient algorithm that breaks down the matrix multiplication operation into'smaller subproblems, solves them recursively, and combines the results to get the final product. The algorithm can be described as follows: 1. Divide each matrix A and B into four equalsized submatrices of size n/2; A= |[A11, A12], [A21, A22]] (811, 812), (821, 822]] 2. Compute the following products recursively: PL=A11* (B12- B22) P2= (ALL + Al2)* B22 = (R21 + A22) * B12 Ignou Study Helper-Sunil Poonia Page 10 pane ye: Toney Stupy Heveee www ignousite.com Naz? Sumie Poowia Pd = A22 * (B21- B11) = PS = (A11 +22) * (B11 +822) Po \12 - A22) * (B21 + B22) P7 = (A11 - A21) * (811 + B12) 3. Compute the resulting submatrices C11, C12, C21, and C22: Ct = P5+P4-P2+ PE c1a=P1+P2 c21= 03+ Pa C22 =P5+P1-P3-P7 4. Combine the resulting submatrices to get the final product: =fle11, 12), {e%1,e22] Analyze this algorithm: The time complexity of this algorithm can be analyzed using the Master Method. In step 2, we are recursively computing 7, matcx products of size n/2, and in step 3, we are computing 4 submatrices of size n/2. Therefore, we can express the time complexity of this algorithm as follows: T(n) = 7T(n/2) + Ofne2) Using the Master Metlod, we car see that Une tine complexity of thivalgor ith is O{n*loy_2 7), which is approximately (0{n*2.81). This is an improvement over the naive algorithm for matrix multiplication, which has a time complexity of O(n°3}. The divide and conquer algorithm is particularly useful for large matrices, where the savings in time become mare significant. Q6. 2) Write the adjacency list and draw adjacency graph for the graphigiven below. 238 Ans. The adjacency list: Vertex Ignou Study Helper-Sunil Poonia Page 11 a Adjacency graph: Vertex: 1 oe Vertex: 2 @ om fet Vertex: 3 Vertex: 4 oe Ignou Study Helper-Sunil Poonia ft Toulon Sry Heeee = SUNIL Pools Page 12 ft Toulon Sry Heeee www ignousite.com = SUNIL POONIA @ 2 ey b) Write and explain the algorithm of Topological sorting. How can you compute time complexity for topological sorting? ‘Ans: Algorithm of Topological sorting: Topological sorting is an algorithm used to sort a directed acyclic graph (DAG] ina linear ordering, such that for every directed edge (u, v), vertex u comes before vertex v in the ordering, In other words, it finds an order in which all nodes can be processed, without violating any dependencies. The algorithm works as follows: 1, Finda vertex with no incoming edges; ie., a vertex with in-degree 0. IF there are multiple sch vertices, choose any 2. Add the vertex to the sorted list and remove it from the graph. 3. Decrease the in-degree of all vertices adjacent to the vartex that was just removed, since their dependency has been resolved. 4, Repeat steps 1-3 until no vertices remain in the graph. The algorithm can be implemented using a queue to Keep track of the vertices with in-degree O. Initially, all vertices with in- degree 0 are added to the queve. Then, the algorithm repeatedly dequeues a vertex, addsit to the sorted list, and updates the in- degree of its neighbors. If any of the neighbors naw have in-degree 0, they are adtied to the queue. ‘Time complexity for topological sorting: The time complexity of Topological sorting is O(V + E), where V is the number of vertices and E is the number of edges in the graph. This is because we visit each vertex and edge exactly once, However, the algorithm can only be applied to DAGs, since it rales on the fact that thera is at least one vertex with in-degree 0. I the graph has cycles, there will be no such vertex, and the algorithm will not work. Overall, Topological sorting is a useful algorithm for dependency resolution in tasks such as scheduling, project management, and software engineering, where tasks need to be completedin 2 specific ordér without violating dependencies. Q7. a) Explain the working of Prim’s algorithm for finding the minimum cost spanning tree with the help of an example. Also find the time complexity of Prim’s algorithm. ‘Ans. Working of Prim’s algorithm for finding the minimum cost spanning tree: Prim's Algorithm is a greedy algorithm that is used to find the minimum spanning tree from 4 graph. Prim’s algorithm finds the subset of edges that includes every vertex of the graph such that the sum of the weights of the edges can be minimized Prim’s algorithm is a greedy algorithm that starts from one vertex and continue to add the edges with the smallest weight until the goal is reached. The steps to implement the prim’s algorithm are given as follows - ‘© First, we have to initialize an MST with the randomly chosen vertex. ‘+ Now, we have to find all the edges thet connect the tree in the above step with the new vertices. From the edges found, select the minimum edge and add it to the tree. ‘© Repeat step 2 until the minimum spanning tree is formed. Ignou Study Helper-Sunil Poonia Page 13, Tonov Stvvy HELPee sonnet com P SUNIL POOHIA sample: The working of prim's algorithm using an example. It will be easier to understand the prim's algorithm using an example. Suppose, a weighted graph is - Step 1 - First, we have to choose a vertex from the above graph. Let's choose B. Step 2 - Now, we have to choose and add the shortest edge from vertex 8. There are two edges from vertex B that are B to C with weight 10 and edge B to D with weight 4. Among the edges, the edge 8D has the minimum weight. So, add it to the MST. Step 3 - Now, again, choose the edge with the minimum weight among all the other edges. In this case, the edges DE and CD are such edges. Add them to MSI and explore the adjacent ot C, 1.€., E and A. So, select the edge De and add it to the MSI, 7 Step 4 - Now, select the edge CD, and add it to the MST. Ignou Study Helper-Sunil Poonia Page 14 s Touou Stvpy HELPER www ignousite.com SUNIL POONIA Step 5 - Now, choose the edge CA. Here, we cannot select the edge CE as it would create a cycle to the graph. So, choose the edge CA and add it to the MST. 7 So, the graph produced in step 5 is the minimum spanning tree of the given graph. The cost of the MST is given below - Cost of MST=4+2+41+3~=10units. Time complexity of Prim’s algorithm: The running time of the prim’ algorithm depends upon using the data structure for the graph and the ordering of edges. Below table shows some choices Data structure used for the minimum edge weight ees Adjacency matrix, linear searching O(lv|2) ‘Adjacency list and binary heap O(JE| log IVI} [Adjacency list and Fibonacci heap O(JE|+ |V| log |VI) Prim’s algorithm can be simply implemented by using the adjacency matrix or adjacency list eraph representation, and to add the edge with the minimum weight requires the linearly searching of an array of weights. It requires O{|V|2) running time. It can be improved further by using the implementation of heap to find the minimum weight edges in the inner loop of the algorithm, The time complexity of the prim’s algorithm is O(E logV) or O[V logV), where E is the no. of edges, and Vis the no. of vertices. 'b) Explain the working of Bellman-Ford algorithm for finding the'shortest path from a single source to all destinations with the help of an example. Also find the time complexity of this algorithm. ‘Ans. Working of Bellman-Ford algorithm for finding the shortest path: Dynamic Programming is used in the Bellman-Ford algorithm. it begins with a starting vertex and calculates the distances between other vertices that 2 single edge can reach. It then searches for a path with two edges, and so on, The Bellman-Ford algorithm uses the bottom-up approach The Bellman-Ford algorithm works by grossly underestimating the length of the path from the starting vertex to all other vertices. The algorithm then iteratively relaxes those estimates by discovering new ways that are shorter than the previously overestimated paths. Algorithm: ‘© The outer loop traverses from 0: n-l ‘© Loop over all edges, check ifthe next node distance > current node distance + edge weight, node distance to “current node distance + edge weight". y =f this case update the next Example: Considerthe below graph: N Ignou Study Helper-Sunil Poonia Page 15 “es Tone Sry Wee ‘auf? SUNIL POONA \www.ignousite.com ‘As we can observe in the above graph that some of the weights are negative. The above graph contains 6 vertices so we will go on relaxing till the 5 vertices. Here, we will relax all the edges 5 times, The loop will iterate 5 times to get the correct answer. If the loop is iterated more than 5 times then also the answer will be the same, i.e, there would be no change in the distance between the vertices, To find the shortest path of the above graph, the first step is note down all the edges which are given below: (A,B), (A, C), (A.D) (BE), (CE), (0, C), (O,F), (EF (CyB) Let's consider the source vertex as 'A’; therefore, the distance value at vertex A is 0 and the distance value at all the ather vertices as infinity shown as below: foo, co Since the graph has six vertices so it will have five iterations. First iteration: Consider the edge (A,B). Denote vertex A’ as 'u' and vertex’ as'v.. Now use the Félaxing formula: diu) luv Since (0 + 6) is less than e, so update div) = d(u) +e(u, v) div)=046=6 Therefore, the distance of vertex 8 is 6. Consider the edge (A, C). Denote vertex dlu)=0 as'u' and vertex. * as 'v'. Now use the relaxing formula: Ignou Study Helper-Sunil Poonia Page 16 ft Toulon Sry Heeee www ignousite.com = SUNIL POONIA div) =e cu, v)=4 Since (0 +4) is less than 2, so update diy) = dtu) + elu, v) diy)=0+4=4 Therefore, the distance of vertex Cis 4, Consider the edge (A, D}. Denote vertex'A’ as ‘u' and vertex ‘D’ as 'v', Now use the relaxing formula: dlu)=0 div) = elu, w=5 sur Since (0 +5) is less than e», so update fe se : aly) = du) + elu, v) Noe div)=04+5= Therefore, the distance of vertex D is 5. Consider the edge (B, £). Denote vertex 'B'as 'u' and vertex 'E’ as.'v', Now use the relaxing formula: diuy=6 div) =o eu, v) Since (6 - 1) is less than =», so update div) = du) + e(u, v) div) =6-1=5 Therefore, the distance of vertex E is 5. Consider the edge (C, £). Denote vertex'C’as'u and vertex’ as 'V. Novy use the relaxing formula: dlu)=4 divy=5 clu, v)= Since (4 + 3) Is greater than 5, so there will@ no updation. The value at vertéXE Is 5 Consider the edgé (0, C). Denote vertex'D' as ‘u' and vertex'C’ as'v’. Now use the relaxing formula dlu)=5 diy=4 ctu, Since (5 2} is less than 4, so update div) = du) + elu, v) div) =5-2=3 Therefore, the distance of vertex Cis 3, Consider the edge (0, F). Denote vertex du) =5. diy) = as‘ and vertex'F’ as 'v. Now use the relaxing formula: (u,v) Since (5 -1} Is less than ©, so update Ignou Study Helper-Sunil Poonia Page 17 “es Tone Sry Wee ‘auf? SUNIL POONA www. lgnousite.com dy) = dfu) + elu, v) divy)=5-1=4 Therefore, the distance of vertex Fis 4 Consider the edge (E, F). Denote vertex 'E' as 'u' and vertex 'F' as 'v'. Now use the relaxing formula: du) =5 dv) = clu, v)=3 Since (5 +3) is greater than 4, so there would be no updation on the distance value of vertex F. Consider the edge (C, 8). Denote vertex 'C’ as"u'and vertex 'B' as 'v', Now Use the relaxing formula: d(u)=3 diy) =6 clu,v)22 ‘Since (3 - 2) is less than 6, so. update dy) = dtu) + lu, v) $ div) =3-2=1 Therefore, the distance of vertex B is 1 ‘Now the first iterations completed, We move to the second Iteration, Second iteration: In the second iteration, we again check all theedges. The first edge is (A, 8). Since (0 + 6) isgreater than 1 so there would be no updation in the vertex B, The next edge is (A, C). Since (0 + 4) is greater than 3-50 there would be no updation in the vertex C. The next edge is (A, D). Since (0 + 5) equals to.5 so there would be no updation in the vertex D. The next edge is (B, E), Since (1 - 2} equals to 0 whichis less than 5 so updats d{y) = tu) + elu, v) d(e) = of8) +018 ,€) =1-1=0 The next edge is {C, F). Since (3 + 3) equals to 6 which is greater than 5 so there would be no updation in the vertex E “The next edge is (, C). Since (5 - 2) equals to 3 ro there would be no updation in the vertex C. The next edge is (D, F). Since (5 - 1) equals to 4 so there would be no updation in the vertex F The next edge is (E, F). Since (5 + 3) equals'to’8 which is greater than 4s0 there would be no updation in the vertex F. The next edge is (C, B). Since (3 - 2] equals to 1° so there would be no updation in the vertex B. esas Oo Third iteration: We will perform the same steps as we did in the previous iterations. We will observe that there will be no updation in the distance of vertices, Ignou Study Helper-Sunil Poonia Page 18 ft Toulon Sry Heeee www ignousite.com = SUNIL POONIA The following are the distances of vertices: wo Bt a _ow os fe NEY Time complexity of Bellman-Ford algorithm: The time complexity of Bellman ford algorithm would be O(EIV| - Q8. a) Explain the process of creating a optimal binary search with the help of an example. ‘Ans. Optional Binary search tree: Optional binary search tree, the nodes in the left subtree have lesser value than the root node and the nodes in the right subtree have greater value than the root node, We know the key values of each node in the tree, and we also know the frequencies of each node in terms of searching means, how much time is required to search anode. The frequency and key-value determine the overall cost of searching a node. The cost of searching is a very important factor in various applications. The overall cost of searching a node should be less. The time required to search 2 node in BST is more than the balanced binary search tree as a balanced binary search tree contains a lesser number of levels than the BST. There is one way that can reduce the cost of a binary search tree is known as an optimal binary search tree Example: Ifthe keys are 10, 20, 30, 40, 50, 60, 70 és Inthe above tree, all the ° on the left subtree are smaller than the value of the root node, and all the nodes on the right subtree are larger than the value of the root node. The maximum time required to search a node is equal to the minimum height of the tree, equal to logn. Now we will see how many binary search trees can be made from the given number of keys. For example: 10, 20, 30 are the keys, and the following are the binary search trees that can be made out from these keys. ‘The Formula for calculating the number of trees: 2n Cn n+4 Ignou Study Helper-Sunil Poonia Page 19 (yey: Tony Stvby HELeeR SUNIL Poowla www ignousite.com . When we use the above formula, then itis found that total 5 number of trees can be created. The cost required for searching an elernent depends on the comparisons ta be made to search an element. Now, we will calculate the average cost of time of the above binary search trees. Inthe above tree, total number of 3 comparisons can be made. The average number of comparisons can be made as: aes average number of comparisons 2 In the above tree, the average number of comparisons that can be made as: aazeg 3 average numberof comparisons z In the above tree, the average number of comparisons that can be made as: Ignou Study Helper-Sunil Poonia Page 20 (yey: Tony Stvby HELeeR ‘maf SUNIL POONA \www.ignousite.com average number of comparisons = “4-5/3 In the above tree, the total number of comparisons can be made as 3. Therefore, the average number of comparisons that can be made as: Inthe above tree, the total number ot comparisons can be made as 3. Theretore, the average number of comparisons that can be made as: average number of comparison In the third case, the number of comparisons is less because the height of the tree is less, so it's@ balanced binary search tree. Till now, we read about the height-balanced binary search tree. To find the optimal binary search tree, we will determine the frequency of searching a key. Let's assume that frequencies associated with the keys 10, 20, 30 are 3, 2,5. ‘The above trees have different frequencies. The tree with the lowest frequency would be considered the optimal binary search tree. The tree with the frequency 17 is the lowest, so it would be considered as the optimal binary search tree. Ignou Study Helper-Sunil Poonia Page 21 ft Toulon Sry Heeee www ignousite.com ey SUNIL POONIA ) Find an optimal parenthesizing of a matrix-chain product whose sequence of dimensions is as follows: Matrix Dimension Al 15*7 AQ 730 A3 30x05 Ad 05x15 AS 15x12 ‘Ans, To find the optimal parenthesizing of a matrix chain product, we can use dynamic programming to minimize the number of scalar multiplications required to compute the product, Let's first calculate the number of scalar multiplications required for each possible parenthesization of the chain. We'll use the following formula to calculate the number of scalar multiplications for a given parenthesization. mij] = min(mfi.k] + mfk+4,j) + pli-t}* plk)*plil) where ml, is the minimum number of scalar multiplications required to compute the matrix product Ali]*Ali+1]*...*AUj], and p is the array of dimensions of the matrices in the chain, Here's the table of values for the given matrix dimensions: Al AQ AB Aa AS AL 0 735 1575 1312 3300 A2 0 -1050 315 735 2520 3 0 525 2625 2250 Aa O 1125 1260 AS 0 2700 From the above table, we can see that the minimum number of scalar multiplications required to compute the product is 3300, We can find the optimal parentheslzation by tracing back the path that leads Lo this minimum value. Here's the optimal parenthesization: ((AL(A2A3}(A4A5}) This parenthesiz: ion will result in the minimum number of scalar multiplications required to compute the matrix chain product. Q8. a) Using the Rabin Karp algorithm, find the pattern string in the given text, Pattern: "ten", Text: "attainthtenbetan”. Write all the steps involved. ‘Ans. Rabin Karp algorithm: The Rabin-Karp string matching algorithm calculates a hash value for the pattern, as well as for each M-character subsequences of text to be compared. Ifthe hash values are unequal, the algorithm will determine the hash value for next M-character sequence. Ifthe hash valiies are equal, the alenrithm will analyze the pattern and the M-character sequence. In this way, there is only one comparison per text subsequence, and character matching is only required when the hash values match. Programe: tmcano> gey fincludesstring he —t int main (}{ = f char txt(80], pat[80]; Ignou Study Helper-Sunil Poonia Page 22. \www.ignousite,com intq; printf ("Enter the container string \n"); scant ("Ss", &txt); printf ("Enter the pattern to be searched \\ scang ("S6s", &pat); int d = 256; printf ("Enter a prime number \n"); scant ("Sed &a); int M = strien (pat); int N= strlen (tet inti j stu0y intp=0, dy nee BA inth for (i= 0;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy