Anda di halaman 1dari 7

Q.Define algorithm? What are its properties? Ans.

An algorithm is a set of instructions that provide step-by-step specifications to perform a task. The properties of an algorithm are: >Input: Specifies the data set that is applied to the algorithm to check its validity. >Output: Specifies the data set that is produced as a result of the algorithm execution. >Definiteness: Specifies that the instructions described in the algorithm should be well defined and should not create any ambiguity. >Termination: Specifies that the instructions described in the algorithm must contain a proper termination condition. >Effectiveness: Specifies that the algorithm take less time and less memory space during its execution. Q. What is debugging and what is profiling? Ans.Debugging is the process of identifying and fixing the errors in a program. Errors in a program can be identified by executing the program with a sample dataset. Profiling is the process of measuring the performance of the program by executing it on different data sets. Performance of a program is measured by recording the time and memory space that the program takes during its execution. Q. Give at least 5 real life examples where we use stack operations. Ans. The real life examples of stacks are: >Bangles in a hand: The bangles wore in a hand follow last-in-first-out (LIFO) strategy of stack. The bangle that you wear first is the last one to be taken out while removing all the bangles from the hand. The bangle that is worn last is the first one to be taken out. >Same circumference circular rings in a pole : The rings having same circumference placed into a pole also follow LIFO strategy. The topmost ring, which was the last to be placed in the pole, is the first one to be taken out. >Sacks full of wheat placed one over other: The sack at the top is removed first and the sack at the bottom is removed last. >The bolts screwed to a single nut : When the bolts are screwed to a single nut, the last screwed bolt is unscrewed first and the bolt that was screwed first is unscrewed in the last. >Battery cells in a torch: The battery cells in a torch also follow the same LIFO strategy of stack. Q. Design an algorithm to generate all prime numbers within the limits l1 and l2. Ans.Algorithm: to generate all prime numbers between the limits l1 and l2. Input: l1 and l2 Output: Prime numbers between l1 and l2 Method: for (n=l1 to l2 in steps of 1 do) prime=true for (i=2 to n/2 in steps of 1 do) if (n % i =0) prime = false break end_if end_for if (prime = true) Display 'Prime number is =', n end_for Q. One of the properties of an algorithm is beauty (true/false) Ans.False Ans:-Profilingis the process of executing a correct program on data sets and measuring the time and space it takes to compute the results?

Q. Give at least 5 real life examples where queue is used. Ans. Real life examples of queue are: >A queue of people at ticket-window: The person who comes first gets the ticket first. The person who is coming last is getting the tickets in last. Therefore, it follows first-in-first-out (FIFO) strategy of queue. >Vehicles on toll-tax bridge: The vehicle that comes first to the toll tax booth leaves the booth first. The vehicle that comes last leaves last. Therefore, it follows first-in-first-out (FIFO) strategy of queue. >Phone answering system: The person who calls first gets a response first from the phone answering system. The person who calls last gets the response last. Therefore, it follows first-in-first-out (FIFO) strategy of queue. >Luggage checking machine: Luggage checking machine checks the luggage first that comes first. Therefore, it follows FIFO principle of queue. >Patients waiting outside the doctor's clinic : The patient who comes first visits the doctor first, and the patient who comes last visits the doctor last. Therefore, it follows the first-in-first-out (FIFO) strategy of queue. Q. Design and develop algorithms for multiplying n integers. Hint: Follow the algorithm to add n numbers given in the text Ans.Algorithm: Multiply_n_Integers Input: integers, number of integers to be multiplied (n), loop variable (i) Q. Develop an algorithm to find the number of Permutations and Combinations for a given n and r. Ans.Permutation of a given number is given by n*(n1)*(n-2)...up to r factors. This is a generalized algorithm for n>2 Algorithm: Permutation of a number for a given rInput: n and r Output: Permutation of n Method: a) per = 1 for (j = n to n - r + 1 in steps of -1 do) //where j is a loop variable per = per*j end_for Display ' Permutation = ', per b) Combination of a number n for a given r is calculated by nCr = nPr / r! Calculate the permutation nPr using the above algorithm Calculate the factorial for r using the algorithm fact = 1 for (j =1 to r in steps of 1 do) //where j is a loop variable fact = fact*j end_for comb = per / fact Display ' Combination =', comb Output: nul, updated Method: Display 'Enter the number of elements' Accept n Display 'Enter elements one by one' for (i = 1 to n in steps of 1 do) Accept a (i) end_for mul = 1 for (i = 1 to n in steps of 1 do) mul = mul*a(i) end_for Display 'multiplication of n integers is = ', mul Q.What is characterstic of stack? Mentions its application. Ans:-the characterstic are stack are as follow >data can be inserted on the top of the stack. >data can only deleted from the top of the stack. >data can not be deleted middle of the stack without first removing all item from the top. Stack are simple data structure that play prominent role in many application are method is next point:>implaementing function cell >maintain the undo list from an application >evaluating an expressio

Q. Design and develop an algorithm for finding the middle element in three numbers. Ans.To find the middle element one has to first sort the numbers in ascending order. The smallest number becomes the first element in the sorted list and the largest number becomes the last element in the sorted list. Consider three numbers 3, 1, and 7. The smallest number amongst these three is 1; therefore, 1 becomes the first element in the sorted list. Amongst 3 and 7, 3 is the second element. The larger number 7 is left out and becomes the last element. Hence the middle number 3 is displayed. Algorithm : Middle_3_Elements Input: a, b, c the three numbers to be sorted, two temporary variables k1, and K2 Output: Middle element in the three numbers. Method: If (a<b) If (a<c) If (b<c) m=b else m=c end if else m=a end if else if (b<c) if (a<c) m=a else m=c end if else m=b end if end if Q. Consider a data set of nine elements {10, 30, 45, 54, 56, 78, 213, 415, 500} and trace the linear search algorithm to find whether the keys 30, 150, 700 are present in the data set or not. Ans.In linear search algorithm, each element in the list is compared with the given key element. If any of the elements in the list is equal to the given key element, the linear search algorithm returns TRUE, else it returns FALSE. Let us apply linear search to find the key element 30 in the given list. >Take the first element 10 from the list and compare it with the key element 30. Clearly the two elements are not equal. >Take the next element 30 from the list and compare it with the key element 30. Clearly, the two elements are equal. The algorithm returns the TRUE value, and the algorithm is terminated. Similarly, search for the key elements 150 and 700. At the end of the search, you will find that the key elements 150 and 700 are not found in the list. Q. Implement all the algorithms designed in the chapter. Ans:-You can implement algorithms discussed in this chapter in various languages, such as C++ and Java. However, you need to know the syntax of the respective language before implementing it. Q.What is linear data structure. Write short note it Ans- A data structure in which every data element has got exactly two neighbors or two adjacent elements except two elements having exactly one data element is called a linear data structure. Otherwise it is called a nonlinear data structure. Q. Trace the binary search algorithm on the same data set and same key elements of problem 2. Ans:-Binary search algorithm can be applied

to the sorted list of elements. Lets first apply the binary search algorithm to find the key element 30 in the following list taken from p

roblem 2: Take the middle element from the list and compare it with the key element. Clearly, the middle element 56 > key element 30. As the key element is smaller than the middle element, the key element can only be present in the left sub list that is as follows: Again, take the middle element from this list and compare it with the key element. Clearly, the middle element 45 > key element 30. As the key element is smaller than the middle element, the key element can only be present in the left sub list that is as follows:

Again, take the middle element from this list and compare it with the key element. Clearly middle element 30= key element 30, therefore, the binary search algorithm returns a TRUE value and the algorithm is terminated. Similarly, search for the key elements 150 and 700. At the end of the search, you will find that the key elements 150 and 700 are not found in the list. Q. Try to know more sorting techniques and make a comparative study of them. Ans.There are various sorting techniques, such as bubble sort, quick sort, and shell sort. Each of these sorting techniques is defined as follows: >Bubble sort: In the bubble sort technique two elements are compared at a time and if the two elements are not in ascending order these elements are interchanged. This process is repeatedly performed throughout the given list until the list is completely sorted. To sort a list of n elements using bubble sort you need to make a total of (n-1)2 comparisons. >Quick sort: The basic idea underlying quick sort is to allow a specific element 'a' within the list 'x' to find its proper position 'j'. The proper position 'j' is found such that it satisfies the following two conditions: The elements on the left hand side of position 'j' are all smaller than or equal to 'a' The elements on the right hand side of position 'j' are all greater than or equal to 'a' If 'a' satisfies these two conditions, then 'a' is the jth smallest element in the list and 'a' is placed at jth position in the finally sorted list. This process is then repeated for sub arrays x [0..j-1] and x [j+1..n-1]. >Shell sort: In shell sort, the given list x is divided into sub lists containing every kth element of the given list. For example, if k=5 then one sub list contains x [0], x [5], x [10]..., another sub list contains x [1], x [6], x [11]..., and so on. The elements of these sub lists are then compared two at a time and if the two elements are not in ascending order, these elements are interchanged. Q. What are the serious shortcomings of the binary search method and sequential search method? Ans.:-A serious shortcoming of the sequential search method is that even if the element that you are trying to search is not present in the given file, the entire file is searched at least once.A serious shortcoming of the binary search method is that it can be applied only to a list in which the elements are arranged in ascending order. Q:-design an itcrative algorithmto find a factorial of a number. Ans:- Mathematically represented as n! . For ex: 5! = 5*4*3*2*1.Algorithm : Factorial Input : n Output : Factorial of n Method fact = 1 for i = n to 1 in steps of 1 do fact = fact*i end_for display factorial = ,fact Algorithm ends

Q. Design an algorithm to find the reverse of a number. Ans. Algorithm: Reverse of a number Input: number Output: Reverse of a number Method: new_number = 0 while (number > 0) n = number % 10 //n denotes a digit extracted from the number number = number / 10 new_number = new_number +n new_number= new_number*10 end while new_number = new_number/10 Display 'Reverse number is =',new_number Q. A number is said to be a palindrome if the reverse of a number is same as the original. Design an algorithm to check whether a number is a palindrome or not. Ans. Algorithm: check whether the number is a palindrome or not Input: number, flag Output: number is a palindrome Method: count = 0 while (number > 0) n = number%10 a(count)=n count = count+1 end while half = count/2 palin = true for (j=1 to half in steps of 1 and k=count to half in steps of 1 do) if (a (j)! =a(k)) palin = false break end if if (palin = true) Display 'Number is a palindrome' else isplay 'Number is not a palindrome' end if end for Q. Implement all the devised algorithms and also the algorithms discussed in the chapter. Ans.You can implement algorithms discussed in this chapter in various languages, such as C++ and Java. However, you need to know the syntax of the respective language before implementing it. Q:-Design recursion algorithm to implement preorder, postorder, inorder travsal of a binary tree. Ans:- Preorder Traversal Algorithm: Preorder Traversal Input: A[], one dimensional array representing the binary tree i, the root address //initially i=1 Output: Preorder sequence Method: If (A[i] != 0) Display(A[i]) Preorder Traversal (A, 2i) Preorder Traversal (A, 2i +1) If end Algorithm ends Inorder Traversal Algorithm: Inorder Traversal Input: A[], one dimensional array representing the binary tree i, the root address //initially i=1 Output: Inorder sequence Method

If (A[i] != 0) Inorder Traversal (A, 2i) Display(A[i]) Inorder Traversal (A, 2i +1) If end Algorithm ends Postorder Traversal Algorithm: Postorder Traversal Input: A[], one dimensional array representing the binary tree i, the root address //initially i=1 Output: Postorder sequence Method: If (A[i] != 0) Postorder Traversal (A, 2i) Postorder Traversal (A, 2i +1) Display(A[i]) If end Algorithm ends Q. Design an algorithm to check whether a given string is a palindrome or not. Ans. Algorithm: check whether the string is a palindrome or not Input: string, flag Output: string is a palindrome Method: count = 0 while (the next character ch in the string is not empty) a(count) = ch ount = count+1 end while half = count/2palin = true for (i=1 to half in steps of 1 and j=count to half in steps of 1 do) if (a (i)! =a (j)) end if f (palin = true) tring is a palielse Display 'String is not a palindrome' end if end for Q. What is the maximum number of nodes in the binary tree of level 7, 8, and 9? Ans.The maximum number of nodes in the binary tree is calculated by 2l+1 - 1 where l is the level of the binary tree. The maximum number of nodes for level 7, 2 7+1 - 1 = 255 The maximum number of nodes for level 8, 2 8+1 - 1 = 511 The maximum number of nodes for level 9, 2 9+1 - 1 = 1023 Q. What is the wastage of memory for a binary tree with 16 nodes represented in a 1D array, 2D array, and a linked representation? Ans.a) For a 1D array, the formula for calculating percentage of memory utilization is: (n -1/2l+1 1)*100 where n represents the number of nodes and l represents the depth of the tree. However, in the given question, the depth has not been specified. Therefore, the percentage memory utilization cannot be calculated. b) For a 2D array, the percentage of memory utilization is: (n -1/n2)*100 = (16 -1/162)*100 = 5.86% Therefore, the wastage of memory in 2D array is 100 - 5.86 = 94.14% c) For a linked list, the percentage of memory utilization is: (n -1/2n)*100 = (16 -1/2*16)*100 = 46.88% Therefore, the wastage of memory in 1D is 100 46.88 = 53.13%

Q.Define stack? Ans:- A stack is an order list in which all insertion and deletion are made at ende, Top In other word we can say that-A stack is a collection of data item that can be access at only one end called top this mean that the item are inserted and deleted at the top the last item that is inserted in a stack is the first one to be deleted. Stack is a liner data structure which work based on strategy last-in first out(lifo) A stack is like an empty box containing books which is list wide enough to held the book in one pile. The book can be placed as well as removed only from the top of the box. The following show the stack of books:-

Now, a new value of k is chosen which is smaller than the previous value of k and the process is repeated again. This process is repeated until the value of k is set to 1 so that the sub list consisting of the entire list is sorted. Q. Hand simulate Insertion Sort on the data set {13, 45, 12, 9, 1, 10, 40} Ans.Let us apply Insertion Sort algorithm on the given list:

Q. For at least 5 binary trees of different depths greater than or equal to 6 of your choice, obtain the preorder, postorder and inorder sequences. Ans.The following figure shows a binary tree with 14 nodes where A is the root node:

Q. Trace out the algorithm Merge Sort on the data set {1,5,2,19,4,17,45,12,6} Ans. Steps to perform Merge Sort on the data set {1,5,2,19,4,17,45,12,6} are: (1,5,2,19,4}{17,45,12,6) The preorder traversal sequence for the above binary tree is: ABDHKMNLECFIJG The infix notation for the above binary tree is MKNHLDBEAIFJCG The postorder notation for the above binary tree is: Q:-What is binary search? Ans:- Binary search method is also relatively simple method. For this method it is necessary to have the vector in an alphabetical or numerically increasing order. A search for a particular item with X resembles the search for a word in the dictionary. The approximate mid entry is located and its key value is examined. If the mid value is greater than X, then the list is chopped off at the (mid-1)th location. Now the list gets reduced to half the original list. The middle entry of the leftreduced list is examined in a similar manner. This procedure is repeated until the item is found or the list has no more elements. On the other hand, if the mid value is lesser than X, then the list is chopped off at (mid+1)th location. The middle entry of the right-reduced list is examined and the procedure is continued until desired key is found or the search interval is exhausted.Binary search is one of the fundamental algorithms in computer science. In order to explore it, we'll first build up a theoretical backbone, then use that to implement the algorithm properly and avoid those nasty offby-one errors everyone's been talking about. ((1,5,2) (19,4)) ((17,45)(12,6)) (((1,5) (2)) ((19)(4))) (((17)(45)) ((12) (6))) ((((1) (5)) (2)) ((19)(4))) (((17)(45)) ((12) (6))) (1,5) (2) (4,19) (17,45) (6,12) (1,2,5) (4,19) (17,45) (6,12) (1,2,4,5,19) (6,12,17,45) (1,2,4,5,6,12,17,19,45) Q. The data structure used by recursive algorithms is Stack Q. When is it appropriate to use recursion? Ans.Recursion is used for repetitive computations in which each action is stated in terms of previous calculation results.

Q. Trace out the algorithm Quick Sort on the data set {12,1,5,7,19,15,8,9,10}. Ans. Steps to perform Quick Sort on the data set{12,1,5,7,19,15,8,9,10} are: {(12),1,5,7,19,15,8,9,10} {(12),1,5,7,10,15,8,9,19} {(12),1,5,7,10,9,8,15,19} {8,1,5,7,10,9,(12),15,19} {(7),1,5,8,10,9}{12}{(15),19} {5,1,(7),8,10,9}{12}{15,19} {(5),1}{7}{(8),10,9}{12}{15}{19} {1,(5)}{7}{(8),9,10}{12}{15}{19} {1,(5)}{7}{(8),9,10}{12}{15}{19} {1}{5}{7}{8}{(9),10}{12}{15}{19} {1}{5}{7}{8}{9}{10}{12}{15}{19} Q. Implement all the algorithms designed in this chapter. Ans. You can implement algorithms discussed in this chapter in various languages, such as C++ and Java. However, you need to know the syntax of the respective language before implementing it. Q. Trace out the algorithm MaxMin on a data set consisting of at least 8 elements. Ans. Steps to perform MaxMin on a data set (2,4,6,3,8,1,9,7) are: (2,4,6,3) (8,1,9,7) ((2,4)(6,3)) ((8,1)(9,7)) In sublist (4,6), max is 6 and min is 4. In sublist (8,9), max is 9 and min is 8. Comparing max and min values of sublist (2,4) and sublist (6,3), value of max is 6 and min is 2. Therefore, for sublist (2,4,6,3) max is 6 and min is 2. Similarly, comparing max and min values of sublist (8,1) and sublist (9,7), value of max is 9 and min is 1. Therefore, for sublist (8,1,9,7) max is 9 and min is 1. Finally, comparing max and min values of sublist (2,4,6,3) and sublist (8,1,9,7), value of max is 9 and min is 1. Q:-What is tree? Ans:-A tree is a non-linear data structure that represents a hieranchical relationship among the various data elements.

Q:-Write th properties of tree Ans:-Some Properties of Tree 1. There is one and only one path between every pair of vertices in a tree, T. 2. A tree with n vertices has n-1 edges. 3. Any connected graph with n vertices and n-1 edges is a tree. 4. A graph is a tree if and only if it is minimally connected. Therefore a graph with n vertices is called a tree if 1. G is connected and is circuit less, or 2. G is connected and has n-1 edges, or 3. G is circuit less and has n-1 edges, or 4. There is exactly one path between every pair of vertices in G, or 5. G is a minimally connected graph. Q. List out the merits and the demerits of recursion. Ans.Merits of recursion are Mathematical functions, such as fibonacci series generation can be easily implemented using recursion as compared to iteration technique. Demerits of recursion are: Many programming languages do not support recursion; hence, recursive mathematical function is implemented using iterative methods. Even though mathematical functions can be easily implemented using recursion, it is always at the cost of execution time and memory space. The recursive programs take considerably more storage and take more time during processing. Q. What is a binary tree? Ans.A binary tree is made up of nodes where each node consists of three elements, left node, right node and a data element. The root node is the topmost node of the binary tree. Q. Differentiate between complete and full binary trees? Ans.The following table lists the differences between complete binary trees and full binary trees: Complete binary trees All the nodes at the previous level are fully accommodated before the next level is accommodated. Number of nodes at the last (n) level may or may not equal to 2n. Leaf nodes may or may not be at the same level. A complete binary tree may or may not be full binary tree. Full binary trees

All levels are maximally accommodated.

Number of nodes at the last (n) level is exactly equal to 2n.

All leaf nodes are at the same level.

A full binary tree is always a complete binary tree.

Each data elements in a tree is called a node. The top most node is called the root. The node of a tree are connected to other to other node throught edges Each node in a tree can have zero or more child node however each node in a tree has exactly one parent. An exception to this rule is the root node, which has no parent

Q:-What is non linear data structures? what is arity or the degree of the elements. Give example of non linear data structure. Ans:- A data structure which is not linear data structure is said to be non-linear data structure. That is, a data structure is said to be non-linear if data elements are allowed to have more than two adjacent elements. Meaning that, a data element can have any number of relations with other data elements. l The number of elements adjacent to a given element is called arity or the degree of the element. i.e., degree = number of relations the element has with others. l There is no upper limit placed on this number. Some of the examples in general are : Friendship among classmates; family structure; University with every component being a sub-component and the relations among them being non-linear; the nervous system of the human body, etc. Few of the specific to Computer Science are: graph, tree.

Q.Design an algorithm to show the different opperaction on the stack? Ans:-Following are the algorithm to show different opperaction on the stack:Algorithm: Create Output: S, Stack created Method: Declare S[SIZE] //Array of size=SIZE Declare and Initialize T=0 //Top pointer to remember the number of elements Algorithm ends Algorithm: Isempty Input: S, stack Output: Boolean Chapter 2 - Elementary Data Structures BSIT 41 Algorithms 11 Method: If (T==0) Return (yes) Else Return (no) If end Algorithm ends Algorithm: Isfull Input: S, stack Output: Boolean Method: If (T==SIZE) Return (yes) Else Return (no) If end Algorithm ends Algorithm: Push Input: (1) S, stack; (2) e, element to be inserted; (3) SIZE, size of the stack; (4) T, the top pointer Output: (1) S, updated; (2) T, updated Method: If (Isfull(S)) then Print (stack overflow) Else T=T+1; S[T] =e If end Algorithm ends Algorithm: Pop Input: (1) S, stack; Output: (1) S, updated; (2) T, updated (3) e element popped Method: If (Isempty(S)) then Print (stack is empty) Else e = S[T] T=T-1; If end Algorithm ends Q:-What is validation of an algorithm? Ans:-Once an algorithm has been devised, it becomes necessary to show that it works. i.e it computes the correct answer to all possible, legal inputs. One simple way is to code it into a program. However, converting the algorithms into programs is a time consuming process. Hence, it is essential to be reasonably sure about the effectiveness of the algorithm before it is coded. This pro at the algorithm level, is called validation. Several mathematical and other empirical methods of validation are available. Providing the validation of an algorithm is a fairly complex process and most often a complete theoretical validation, though desirable, may not be provided. Alternately, algorithm segments, which have been proved else where may be used and the overall working algorithm may be empirically validated for several test cases. Such methods, although suffice in most cases, may often lead to the presence of unidentified bugs or side effects later on. Q.Write short note on-devide and conque technique? Ans. The devide and conque technique is analgorithm design technique that involves breaking down the problem recursively into subproblems become so small that they can be directly solved. The solution to be subproblems are then combine to give a solution to the original problem. Devide and conquer is a powerfull approchfor solving conceptally difficult problems,it simply requires you to find the wa

1.Breaking the problem into subproblem 2. Soloving the trivial case 3. combining the solutions to the subproblems to solve the original problem Divide and conquie often provide a natural way to design offcient algorithm. Consider an example where we have to find the minium value in the list of numbers. The list is shown an following fifur:-7,3,4,2,1,9,8,10 List of numbers To find the minuam value we can divid the list into halves as shown in the following figure:7,3,4,21,9,8,10 List of number To find the minimum valuewe can divid the list into two halves as show in the following figure:7,3,4,2 1,9,8,10 List divid into two equal ports:Again divid each of the two list halves s show in the following figure:-7,3 4,2 1,9 8,10 List divid into four eaqual parts:Now there are only two elements in each list. At this stage the two elements and each list to find the minimum of the two. The minimum value from each of the four lists is shown in the following figure:-3,2,1,8 Minimum value in the four list Again compare the first two minimum values to determine their minimum. Also compare the lase two minimum value thus abtained are shoe in the following figure:- 2,1 Mimimum values in two halves original list Again compare the two final minimum value to obtain the overall minimum value, which is one is the precoding example. Q:-Design twodifferent algorithm to check if a given number is prime. Ans:-Here we keep dividing a number from 2 to half the value of that number. For ex: if 47 is the number under consideration for primality testing then we would divide 47 form 2 to 47/2(23.5 approx. 24) and check whether any number in this interval performs a division operation on 47 such that there is no remainder. If so then the given number is not prime. But in the case of 47 no number between 2 and 24 performs such sort of division operation and hence it is declared as a prime number. Algorithm: Primality_Testing (First approach) Input: n , number flag, test condition Output: flag updated Method flag = 0 for(i=2 to n/2 in steps of +1 and flag = 0) if( n % i = 0) // n mod i flag = 1 end-if end-for if(flag = 0) Chapter 3 - Some Simple Algorithms BSIT 41 Algorithms 31 display Number is prime else display Number is not prime end_if Algorithm ends Second Approach It is proved in number theory that instead of setting the interval of divisor to n/2 we can simply set that to square root of the given number under consideration of Primality and it would work perfectly fine as the previous algorithm. Note that in this algorithm we achieve the same result with lesser number of operations because we reduce the size of the interval. Algorithm: Primality_Testing (Second approach) Input : n , number flag, test condition Output : flag updated Method flag = 0 for(i=2 to square_root(n) in steps of +1 and flag = 0) if( n % i = 0) // n mod i flag = 1 end_if end-for if(flag = 0) display Number is prime else display Number is not prime end_if

Q:-Write a program to find the root of a quadratic equation? Ans:-The general form of the Quadratic equation is ax2+bx+c=0. And these are two roots of the equation. The term (b2-4ac) in the solution to the root is called the discriminant of the root. Basically the roots can be real or imaginary in nature. If the roots are real in nature then they can be either real and distinct, or both of them can be equal. If they are imaginary the roots exists in complex conjugates. The problem of identifying the nature of the roots is achieved in checking the nature of the discriminant. The nature of the discriminant reflects the nature of the solution of the quadratic equation. If the discriminant is negative then the roots will be of imaginary in nature. i.e if (b2-4ac) = some ve value. And these are two roots of the equation. The term (b2-4ac) in the solution to the root is called the discriminant of the root. Basically the roots can be real or imaginary in nature. If the roots are real in nature then they can be either real and distinct, or both of them can be equal. If they are imaginary the roots exists in complex conjugates. The problem of identifying the nature of the roots is achieved in checking the nature of the discriminant. The nature of the discriminant reflects the nature of the solution of the quadratic equation. If the discriminant is negative then the roots will be of imaginary in nature. i.e if (b2-4ac) = some ve value. Then is complex in nature, because square root of any negative number always results in an imaginary result. Now the roots R1 and R2 has imaginary parts and hence they are imaginary in nature. Now the other possibility is that the roots being real. For that to happen the disciminant (b2-4ac) = 0. If it is equal to zero than the discriminant vanishes and hence the roots are real and equal,which are R1 = R2 = -b/2a. In case (b2-4ac) > 0 , then the roots are real and distinct. The algorithm to find the solution to a quadratic equation is given below. Algorithm: Quadratic_solver Input : a,b,c the co-efficients of the Quadratic Equation Output : The two roots of the Equation Method disc = ((b*b) (4*a*c)) if (disc = 0) display roots are real and equal r1 = -b/2a r2 = -b/2a display r1 display r2 else if(disc>0) display roots are real and distinct r1 = (-b+sqrt(disc))/2a r2 = (-b-sqrt(disc))/2a else display roots are complex display real part,-b/2a display imaginary part, sqrt(absolute_value_of(disc)) display the two root exists in conjugates end_if Algorithm ends Q:-How to find the quadrants of a given coordinate posting? Ans:-The problem of finding the Quadrant in which a given co-ordinate position(x,y) lies is a Computer Graphics problem. In a Cartesian system if both X and Y co-ordinates are positive then it is said to be First Quadrant of the Cartesian plane. If X and Y are both negative then it said to be Third Quadrant of the Cartesian plane. If X is negative and Y is positive then it is said to be Second Quadrant and in case if X is positive and Y is negative then it said to be in the Fourth Quadrant of the Cartesian plane. The Diagram of the Cartesian plane is given in Fig. 3.1 below to

make facts more cleare

The co-ordinate positions thus entered have to fall in either of those Quadrant based on the sign of the X and Y co-ordinate positions. Algorithm : Quadrant_Finder Input : x, X co-ordinate y, Y co-ordinate Output : Corresponding Co-ordinate Method If( x >=0) If(y>=0) Display I Quadrant Else Display IV-Quadrant end_if else If(y>=0) Display II Quadrant Else Display III-Quadrant end_if end_if Algorithm ends Q:-Design an algorithm to generate all prime number between 10 and 20 Ans:- Algorithm: to generate all prime numbers between the limits 10 and 20. Input: 10 and 20 Output: Prime numbers between l1 and l2 Method: for (n=10 to 20 in steps of 1 do) prime=true for (i=2 to n/2 in steps of 1 do) if (n % i =0) prime = false break end_if end_for if (prime = true) Display 'Prime number is =', n end_for algorithm end Q:-Design a recursive algorithm to find afootarial of given number? Ans:- The factorial of a number n = n * (n-1) * (n-2)* * 3 * 2 * 1. An iterative way of obtaining the factorial of a given number is to put a for loop to repeat the multiplication n times. We start with 1, then evaluate 1 * 2, then that product * 3, .*(n-1). The factorial of a number can also be obtained recursively. Suppose we are asked to evaluate N!. If we somehow know (N-1)! then we can evaluate N! = N*(N1)!. But how do we get (N-1)!? The same logic can be employed to evaluate (N-1)! = (N-1) * (N-2)!. The problem of finding the factorial of a given number can be recursively defined as Thus, the algorithm developed to compute the factorial of a given number is Algorithm: Factorial Input: n, the integer value whose factorial is to be computed Output: factorial of n Method: If (n==1) then Return (1) Else Return (n * factorial (n-1) If end Algorithm ends

Q:- Trace out the algorithm MaxMin on a data set consisting of atleast 8 elements. Ans:-Step to perform manmin on a data set (2,4,6,3,8,1,9,7) are:(2,4,6,3) (8,1,9,7) ((2,4) (6,3)) ((8,1) (9,7)) In sublist (4,6) max is 6 and min is 4. In sub lidt (8,9), max is 9 and min 8. Comparing max and min value of sublist(2,4) and sublist(6,3) value of max is 6 and min is 2. Therefor , for sublist (2,4,6,3) max is 6 and min 2. Similarly, comparing max and minvalue of sublist (8,1) and sub list (9,7) value of max is 9 and min is 1 Finaly comparing max and min value of sublist (2,4,6,3) and sub list (8,1,9,7) value of max is 9 and min is 1 Q:-What is queus? Design an algorithm to show different operations on a queue. Ans:- A queue is an ordered list in which all insertions take place at one end called the rear end, while all deletions take place at the other end called the front end. Queue is a linear data structure which works based on the strategy first-in-first out (FIFO). Unlike stacks, queues also arise quite naturally in the computer solution of many problems. Perhaps the most common occurrence of a queue in computer applications is for scheduling of jobs. A minimal set of useful operations on queue includes the following. Create ( ) g Q; Insertion (Q, e) g updated Q; Deletion (Q) g Q, e; Isfull (Q) g Boolean; Isempty (Q) g Boolean; Front (Q) g e; Back (Q); Destroy (Q); Following are the algorithms for some functions of queue. Algorithm: Create Output: Q, Queue created Method: Declare Q[SIZE] //Array with size=SIZE Declare and Initialize F=0, R=0 //Front and Rear pointers to keep track of the front element and the rear element respectively Algorithm ends Algorithm: Isempty Input: Q, Queue Output: Boolean Method: If (F==0) Return (yes) Else Return (no) If end Algorithm ends Algorithm: Isfull Input: Q, Queue Output: Boolean Method: If (R==SIZE) Return (yes) Else Return (no) If end Algorithm ends 14 Algorithm: Front Input: Q, Queue Output: element in the front Method: If (Isempty (Q)) Print no front element Else Return (Q[F]) If end Algorithm ends Algorithm: Rear Input: Q, Queue Output: element in the rear Method: If (Isempty (Q)) Print no back element Else Return (Q[R]) If end Algorithm ends Algorithm: Insertion Input: (1) Q Queue; (2) e,element to be inserted; (3) SIZE, size of the Queue; (4) F, the front pointer; (5) R, the rear pointer Output: (1) Q,updated; (2) F,updated; (3)R,updated

Method: If (Isfull (Q)) then Print (overflow) Else R=R+1; Q[R]=e If (F==0) F=1; If end If end Algorithm ends Algorithm: Deletion Input: (1) Q, Queue; (2) SIZE, size of the Queue; (3) F, the front pointer; (4) R, the rear pointer Output: (1) Q, updated; (2) F, updated; (3) R, updated; (4) e, element if deleted; Method: If (Isempty (Q)) then Print (Queue is empty) Else e = Q[F] If (F==R) F=R=0; Else F=F+1; If end If end Algorithm ends Q:-What is circular queue? Design an algorithm for its function. Ans:- A circular queue uses the same conventions as that of linear queue. Using Front will always point one position counterclockwise from the first element in the queue. In order to add an element, it will be necessary to move rear one position clockwise. Similarly, it will be necessary to move front one position clockwise each time a deletion is made. Nevertheless, the algorithms for create (), Isfull (), Isempty (), Front () and Rear () are same as that of linear queue. The algorithms for other functions are Algorithm: Insertion Input: (1) CQ, Circular Queue; (2) e, element to be inserted; (3) SIZE, size of the Circular Queue; (4) F, the front pointer; (5) R, the rear pointer Output: (1) CQ, updated; (2) F, updated; (3) R, updated Method: If (Isfull (CQ)) then Print (overflow) Else R=R mod SIZE + 1; CQ[R] =e If (Isempty (CQ)) F=1; If end If end Algorithm ends Algorithm: Deletion Input: (1) CQ, Circular Queue; (2) SIZE, size of the CQ; (3) F, the front pointer; (4) R, the rear pointer Output: (1) CQ, updated; (2) F, updated; (3) R, updated; (4) e, element if deleted; Method: If (Isempty (CQ)) then Print (Queue is empty) Else e = CQ[F] If (F==R) F=R=0; Else F=F mod SIZE +1; If end If end Algorithm ends

Q:- What is a binary tree? What are the properties of a binary tree? Mentions its applications. Ans.A binary tree is made up of nodes where each node consists of three elements, left node, right node and a data element. The root node is the topmost node of the binary tree. Is show in the following figure:

in the preceding binary tree, node B is a left child and node C is a right child of node A.there are some variants of binary tree with some additional characteristics. Binary Tree can be represented using the two methods: Static , Dynamic tree 1)Static binary tree:-A binary tree said to be static binary if every node,except for the root nodehave non empty left and right children.

Else If ( p q-1) Then If a(p) > a(q) Then Chapter 5 - Recursion BSIT 41 Algorithms 51 max = a(p) min = a(q) Else max = a(q) min = a(p) If End Else m (p+q)/2 max-min(p,m,max1,min1) max-min(m+1,q,max2,min2) max f large(max1,max2) min f small(min1,min2) If End If End Algorithm Ends. Q:-Design recursine algorithm to travers a binary tree represented in link list in inorder , preorder and postorder. And hand simulate your algorithm with an example. Ans:- Algorithm: Pre-order Traversal Input: bt, address of the root node Output: Preorder sequence Method: if(bt != NULL) { Display([bt].data) Pre-order Traversal([bt].Lchild) Pre-order Traversal([bt].Rchild) } Algorithm ends. Algorithm: In-order Traversal Input: bt, address of the root node Output: Inorder sequence Method: if(bt != NULL) { In-order Traversal([bt].Lchild) Display([bt].data) In-order Traversal([bt].Rchild) } Algorithm ends. Algorithm: Post-order Traversal Input: bt, address of the root node Output: Postorder sequence Method: if(bt != NULL) { Post-order Traversal([bt].Lchild) Post-order Traversal([bt].Rchild) Display([bt].data) } Algorithm end Q:-What is recursion? Which data structure is use for a recursion. Ans:- We now understand that recursion is a process of defining a process/ problem/ an object in terms of itself. Recursion is one of the applications of stacks. The recursive mechanisms are extremely powerful, but even more importantly; many times they can express an otherwise complex process, very clearly. Any program can be written using recursion. Of course, the recursive program in that case could be tougher to understand. Hence, recursion can be used when the problem itself can be defined recursively. is one of the very powerful programming concepts, supported by most of the languages. At the same time, it is also a fact that most beginners are confused by the way it works and are unable to use it effectively. Also, some languages may not support recursion. In such cases, it may become necessary to rewrite recursive functions into nonrecursive ones. The general procedure for any recursive algorithm is as follows,1. Save the parameters, local variables and return addresses. 2. If the termination criterion is reached perform final computation and go to step 3, otherwise perform final computations and go to step 1. 3. Restore the most recently saved parameters, local variables and return address and go to the latest return address. The data structure used by recursive algorithms is Stack.

Q:-Constract a binary tree of over and traverse them in inorder, preorder, postorder and produce the corresponding sequence. Ans:-

2)Full binary tree:- A complete binary tree is called full binary tree if, >All the leaves are present only at the last level. >All the nodes at the previous level are fully accommodated. 3)Compute binary tree:-A binary tree which all levels, exapt possibly the deepest level all node are as far left as possible.

Pre-Order Traversal In this traversal, the nodes are visited in the order of root, left child and then right child. i.e., 1 Visit the root node first. 2 Go to the first left sub-tree. 3 After the completion of the left sub-tree, Go to the right sub-tree. Here, the leaf nodes represent the stopping criteria. We go to the sibling sub-tree after the traversal of a sub-tree. The pre-order traversal sequence for the binary tree shown in Fig. 6.3 is : A B D E G H C F IJK In-Order Traversal In this traversal, the nodes are visited in the order of left child, root and then right child. i.e., the left sub-tree is traversed first, then the root is visited and then the right sub-tree is traversed. Here also, the leaf nodes denote the stopping criteria. The in-order traversal sequence for the above considered example (Fig. 6.3) is: D B G E H A F J I K C Post_Order Traversal In this traversal, the nodes are visited in the order of left child, right child and then root. i.e., the left sub-tree is traversed first, then the sibling is traversed next. The root is visited last. The post-order traversal for the above example (Fig. 6.3) is: D G H E BJKIFCA Q:-Design an algorithm to check whenever the given group is connected. Ans:-Algorithm: graphconnectivity_testing Input: pathbv, Boolean Path, number(test condition) Output: path updated Method: If(path=1) Pathbv=true Displaygraph is connected End if Algorithm end Q:-Design an interative and recursive algorithm to generate Fibonacci sequence of length n. Ans:-Iterative Algorithm Algorithm : Fibonacci_Series Input : n, the number of elements in the series Output : fibonacci series upto the nth element Method a = -1 b=1 for(i=1 to n in steps of +1 do)

c=a+b display c a=b b=c end_for Algorithm ends Thus, following is the recursive algorithm designed to find the nth Fibonacci number Algorithm: Fibonacci Input: n, the position at which the Fibonacci number has to be computed Output: nth Fibonacci number Method: If (n==0) Return (0) Else If (n == 1) Return (1) Else Return (Fibonacci (n-1) + Fibonacci (n-2)) If end If end Algorithm ends Q:-Design an iterative to search for an element using binary tree. Ans:- The algorithm for binary search is as follows, Algorithm : binary search Input : A, vector of n elements K, search element Output : low index of k Method : low=1,high=n While(low<=high-1) { mid=(low+high)/2 if(k<a[mid]) high=mid else low=mid if end } while end if(k=A[low]) { write(search successful) write(k is at location low) exit(); } else write (search unsuccessful); if end; Algorithm ends. Algorithm : binary search Input : A, vector of n elements K, search element Low, the lower limit High, the upper limit //initially low=1 and high=n the number of elements Output : the position of the K Method : if (low <= high) mid=(low+high)/2 if( a[mid] == K) return(mid) else if (a[mid]< K) Binary search(A, K, Low, mid) else Binary Search(A, K, High, mid) if end if end else return(0) if end Algorithm ends.

This type offer a large number of application in various fielde. Some of the comman applications of this tree includes: 1)Indexing 2)Encoding messagevsing 3)Arithmetic expression evalutions Q:-Design an algorithm in iteration and recursionto find minmumand maximum elements in an elements. Ans:- Algorithm: Max-Min Input: p, q, the lower and upper limits of the dataset max, min, two variables to return the maximum and minimum values in the list Output: the maximum and minimum values in the data set Method: If (p = q) Then max = a(p) min = a(q)

Q:-Write short note on:1)Incidence matrix 2)Degree 3)Isolated vertex 4)Nullgraph 5)Path Ans:-Incidence matrix:- Let G be a graph with n vertices, e edges, and no self-loops. Define an n by e matrix A =[aij], whose n rows correspond to the n vertices and the e columns correspond to the e edges, as follows: The matrix element Aij = 1, if jth edge ej is incident on ith vertex vi, and = 0, otherwise. abcdefgh v1 0 0 0 1 0 1 0 0 v2 0 0 0 0 1 1 1 1 v3 0 0 0 0 0 0 0 1 v4 1 1 1 0 1 0 0 0 v5 0 0 1 1 0 0 1 0 v6 1 1 0 0 0 0 0 0 Such a matrix A is called the vertex-edge incidence matrix, or simply incidence matrix. Matrix A for a graph G is sometimes also written as A(G). A graph and its incidence matrix are shown in Fig. 2.4 and Fig. 2.5 respectively. The incidence matrix contains only two elements, 0 and 1. Such a matrix is called a binary matrix or a (0, 1)-matrix. Degree:- The number of elements adjacent to a given element is called arity or the degree of the element. i.e., degree = number of relations the element has with others. Isolated vertex:- A vertex having no incident edge is called an isolated vertex. In other words, isolated vertices arevertices with zero degree.

v2

v4

v3

v5 v1 v6

Nullgraph:- Such a graph, without any edges, is called a null graph. In other words, every vertex in a null graph is an isolated vertex.A null graph of six vertices is shown in Fig. v1 v5 v3 v2 v4 Path:- If a walk has the restriction of no repetition of vertices and no edge is retraced it is called a path Connected graph:- If there is a walk to every vertex from any other vertex of the graph then it is called a connected graph. Q:-Define walk, path and connected graph? Ans:- A walk is a sequence of alternating vertices and edges, starting with a vertex and ending with a vertex with any number of revisiting vertices and retracing of edges. If a walk has the restriction of no repetition of vertices and no edge is retraced it is called a path. If there is a walk to every vertex from any other vertex of the graph then it is called a connected graph Q. Draw a connected graph that becomes disconnected when any edge is removed from it. Ans. The following figure shows a graph that becomes disconnected when any edge is removed from it: v6

Q:- Get to know about few more sorting algorithm and people a brif note on them. Ans:-Bubble sort:-Bubble short is one of the most popular sorting methods. Bubble short can be viewed as a selection sort become this method is also based on successively selecting the smallest elements second smallest elements, ets as in the case of any other selection sort. In order to find the successive smallest elements, the method relef having on the exchange of adjacent. Because of this the method of often classed as shorting by exchange. Insertion Sorting The first class of sorting algorithm that we consider comprises algorithms that sort by insertion. An algorithm that sorts by insertion takes the initial, unsorted sequence, { ... } 1: 2: 3 n S = s s s s , and computes a series of sorted sequences n S' S' : ... : S' 0: 1 , as follows: 1. The first sequence in the series, 0 S ' is the empty sequence. i.e., ' {} 0 S = . 2. Given a sequence 0 S ' in the series, for 0 i n , the next sequence in the series, 1 'i+ S , is obtained by inserting the (i +1)th element of the unsorted sequence 1 'i+ S into the correct position in i S' . Each sequence i S' , 0 i n , contains the first i elements of the unsorted sequence S. Therefore, the final sequence in the series, n S' , is the sorted sequence we seek. i.e., n S ' = S' . Fig. 4.1 illustrates the insertion sorting algorithm. The figure shows the progression of the insertion sorting algorithm as it sorts an array of ten integers. The array is sorted in place. I.e., the initial unsorted sequence, S, and the series of sorted sequences, n S' S ' : ... : S ' 0: 1 , , occupy the same array. In the ith step, the element at position i in the array is inserted into the sorted sequence i S' which occupies array positions 0 to (i-1). After this is done, array positions 0 to i contain the i+1 elements of 1 'i+ S . Array positions (i+1) to (n-1) contain the remaining n-i1 elements of the unsorted sequence S. Selection Sorting:-Such algorithms construct the sorted sequence one element at a time by adding elements to the sorted sequence in order. At each step, the next element to be added to the sorted sequence is selected from the remaining elements. Because the elements are added to the sorted sequence in order, they are always added at one end. This is what makes selection sorting different from insertion sorting. In insertion sorting elements are added to the sorted sequence in an arbitrary order. Therefore, the position in the sorted sequence at which each subsequent element is inserted is arbitrary.Both selection sorts described in this section sort the arrays in place. Consequently, the sorts are implemented by exchanging array elements. Nevertheless, selection differs from exchange sorting because at each step we select the next element of the sorted sequence from the remaining elements and then we move it into its final position in the array by exchanging it with whatever happens to be occupying that position. Quick sort: The basic idea underlying quick sort is to allow a specific element 'a' within the list 'x' to find its proper position 'j'. The proper position 'j' is found such that it satisfies the following two conditions: The elements on the left hand side of position 'j' are all smaller than or equal to 'a' The elements on the right hand side of position 'j' are all greater than or equal to 'a' If 'a' satisfies these two conditions, then 'a' is the jth smallest element in the list and 'a' is placed at jth position in the finally sorted list. This process is then repeated for sub arrays x [0..j-1] and x [j+1..n-1]. Shell sort: In shell sort, the given list x is divided into sub lists containing every kth element of the given list. For example, if k=5 then one sub list contains x [0], x [5], x [10]..., another sub list contains x [1], x [6], x [11]..., and so on. The elements of these sub lists are then compared two at a time and if the two elements are not in ascending order, these elements are interchanged.Now, a new value of k is chosen which is smaller than the previous value of k and the process is repeated again. This process is repeated until the value of k is set to 1 so that the sub list consisting of the entire list is sorted

Q:-Design conventional iteratine algorithm to traverse a binary tree represented in link list inorder, preorder and postorder Ans:-Inorder 1) Set ver to root 2) if ver=Null, print null tree, go to step 9 3)Set vars flag to 1, puch var structure 4)Set var to vers left 5)if var != null then goto step 3 6)var=pop() 7) If(vars flag==2) then goto step 8 Else A) Print var data B) Set vars flag to 2 C) Puch var structure D) Set var to vars root E) Goto step 5 8) If(stack ! empty) then goto step 6 9) Stop Preorder 1) Set ver to root 2) if ver=Null, print null tree, go to step 9 3)Print var data, set var flag to 1, push var structure 4)Set var to vers left 5)if var != null then goto step 3 6)var=pop() 7) If(vars flag==2) then goto step 8 Elsse A) Set vars flag to 2 B) Puch var structure C) Set var to vars right D) Goto step 5 8) If(stack ! empty) then goto step 6 9) Stop Postorder 1) Set ver to root 2) if ver=Null, print null tree, go to step 9 3)Set vars flag to 1, puch var structure 4)Set var to vers left 5)if var1= null) then goto step 3 6)var=pop() 7) If(vars flag==2) then print vars data Else A) Set vars flag to 2 B) Puch var structure C) Set var to vars right D) Goto step 5 8) If(stack not empty) then goto step 6 9) Stop Q:- Different between static allocation and dynamic allocation Ans:- In static allocation, we have to ways of representing the binary tree. One is through the use of adjancy matrices and the other through the use of single dimemsional array representation. The other alternative way of represention of the binary tree is based on link allocation, dynamic allocation method. 5. Hand simulate Insertion Sort on the data set {13, 45, 12, 9, 1, 10, 40} Ans.Let us apply Insertion Sort algorithm on the given list:

Q:-Write a recursive algorithm to find sum of a number. Ans:- algorithm to achieve this is as follows Algorithm : Sumnum Input : n, the upper limit Output : Sum of first n positive integers Method: if (n <= 0) // We only want positive integers return 0; else if (n == 0) // Our terminating condition return 1; else return (n + Sumnum( n -1 ); // recursive step if end if end Algorithm ends Q:-Design an algorithm to check whether the given graph is connected using the adjency matrix representation Ans:- 1 Locate the root (the column sum is zero for the root) 2 Display 3 Push in to the stack 4 Scan the row in search of L for the left child information 5 Pop from the stack 6 Scan the row in search of R for the right child information 7 Check if array IsEmpty(). 8 Stop Sequencing the above stated steps helps us in arriving at preorder, inorder and postorder traversal sequences. Q:- Sketch all binary trees with six pendent edges. Ans.:-The following figures show binary trees with six pendent edges: Binary Tree with Six Pendent Edges

The preceding figures, A, B, and C, show three examples of binary trees having six pendent edges. All the binary trees having six leaf nodes come under this category. Q:-Write an algorithm to short list of elements using quick sort and hand simulate on a data set of atlest 9 elements Ans:- Algorithm: QuickSort Input: p, q, the lower and upper limits of the list of elements A to be sorted Output: A, the sorted list Method: If (p < q) j = q+1; PARTITION (p, j) QuickSort(P, j-1) Quicksort(j+1, q) If end Algorithm ends Algorithm: PARTITION Input: m, the position of the element whose actual position in the sorted list has to be found p, the upper limit of the list Output: the position of mth element Method: v = A(m); i = m; Repeat Repeat i = i+1 Until (A(i) e> v); Repeat p=p-1 Until (A(p) d v); If (i < p) INTERCHANGE(A(i), A(p)) If end Until (i e p) A(m) = A(p) ; A(p) = v; Algorithm ends

Q:-Explain the illustrate insertion sort algorithm to short a list n nos. Ans:- The first class of sorting algorithm that we consider comprises algorithms that sort by insertion. An algorithm that sorts by insertion takes the initial, unsorted sequence, { ... } 1: 2: 3 n S = s s s s , and computes a series of sorted sequences n S' S' : ... : S' 0: 1 , as follows: 1. The first sequence in the series, 0 S ' is the empty sequence. i.e., ' {} 0 S = . 2. Given a sequence 0 S ' in the series, for 0 i n , the next sequence in the series, 1 'i+ S , is obtained by inserting the (i +1)th element of the unsorted sequence 1 'i+ S into the correct position in i S' . Each sequence i S' , 0 i n , contains the first i elements of the unsorted sequence S. Therefore, the final sequence in the series, n S' , is the sorted sequence we seek. i.e., n S ' = S' . Fig. 4.1 illustrates the insertion sorting algorithm. The figure shows the progression of the insertion sorting algorithm as it sorts an array of ten integers. The array is sorted in place. I.e., the initial unsorted sequence, S, and the series of sorted sequences, n S' S ' : ... : S ' 0: 1 , , occupy the same array. In the ith step, the element at position i in the array is inserted into the sorted sequence i S' which occupies array positions 0 to ( i-1). After this is done, array positions 0 to i contain the i+1 elements of 1 'i+ S . Array positions (i+1) to (n-1) contain the remaining n-i1 elements of the unsorted sequence S. As shown in Fig. 4.1, the first step (i=0) is trivial inserting an element into the empty list involves no work. Altogether, n-1 non-trivial insertions are required to sort a list of n elements.

Output: A, Sorted list Method: If (low<high) mid (low + high)/2 MERGESORT(low, mid) MERGESORT (mid, high) MERGE(A, low, mid, high) If end Algorithm ends Algorithm: Merge Input: low, mid, high, limits of two lists to be merged i.e., A(low, mid) and A(mid+1, high) A, the list of elements Output: B, the merged and sorted list Method: h = low, i = low, j = mid + 1; While ((h d mid) and (j d high)) do If (A(h) d A(j) ) B(i) = a(h); h = h+1; else B(i) = A(j); j = j+1; If end i = i+1; If (h > mid) For k = j to high B(i) = A(k); i = i+1; For end Else For k = h to mid B(i) = A(k); i = i+1 For end If end While end Algorithm ends Steps to perform Merge Sort on the data set {1,5,2,19,4,17,45,12,6} are: (1,5,2,19,4}{17,45,12,6) ((1,5,2) (19,4)) ((17,45)(12,6)) (((1,5) (2)) ((19)(4))) (((17)(45)) ((12) (6))) ((((1) (5)) (2)) ((19)(4))) (((17)(45)) ((12) (6))) (1,5) (2) (4,19) (17,45) (6,12) (1,2,5) (4,19) (17,45) (6,12) (1,2,4,5,19) (6,12,17,45) (1,2,4,5,6,12,17,19,45) Q:-Define circular queue? What are its advantages. Ans:-A circular queue implemented of an array in the form of a ring. In a circular queue if the last index is occupied by an element then we start inserting the element from the beginning provided there is a free space. Its advantage is that it make more utilization of memory then the linear queue. Q:-Defference between recursion and iteration. Ans:-Recursion is a top down approach of a problem solving. It divided the problem into the parts and select a key step postponing the rest where as iteration is a bottam up approach of solving problem. An interative approach begins with what is known and this constructs the solution step by step. Q:-What is the limitations of linear queue? How do you overcome using circular queue? Ans:-Limitation of linear queue is that it does not make most use of available memory spece is available. If we have inserted element at the last index and there is space available then alsowe can not insert element. We can overcome this limitation using circular queue because circular makes more utilization available then we can insert element in a circular queue. Q:-How can one validatethe designed algorithm? Ans:-one an algorithm has been designed it become necessary to show that it work. i.e. it compute the correct answer to all possible legar input. One simple way is to code it into a program. It is essential to be reasonably sure about the effectiveness of the algorithm before it is coded. This process, at the algorithm level is called validation. The validation of an algorithm is a fairly complex process and most often a complete theoretical validation, through desirable may not be provided. Alternately, algorithm segments, which have been provide else where may beused and the overall working algorithm may be empirically validate for several test cases. Q;- For at least 5 binary trees of different depths greater than or equal to 6 of your choice, obtain the preorder, postorder and inorder sequences. Ans.The following figure shows a binary tree with 14

nodes where A is the root node:

Binary Tree with 14 Nodes The preorder traversal sequence for the above binary tree is: ABDHKMNLECFIJG The infix notation for the above binary tree is: MKNHLDBEAIFJCG The postorder notation for the above binary tree is: MNKLHDEBIJFGCA

Algorithm : Insertion Sort Input : n, Size of the input domain a[1..n], array of n elements Output : a[1..n] sorted 42 Method for j= 2 to n in steps of 1 do item = a[j] i = j-1 while((i>=1) and (item<a[i])) do a[i+1] = a[i] i = i-1 while end a[i+1] = item for end Algorithm ends Q:-Design a recursive algorithm to sort a list of elements using marge sort and hand simulate on a data set of atleast 9 elements Ans:- Algorithm: MERGESORT Input: low, high, the lower and upper limits of the list to be sorted A, the list of elements

Anda mungkin juga menyukai