0% found this document useful (0 votes)
21 views48 pages

FDS Quality Solved Paper Endsem May 2024 PyqSPOT

The document contains an examination paper for a course on Data Structures, featuring a total of 8 questions covering various topics such as sorting algorithms (bubble sort, selection sort), searching algorithms (binary search, Fibonacci search), linked lists, and queue implementations. Each question requires detailed explanations, pseudocode, and step-by-step executions for algorithms, along with complexity analysis. The paper emphasizes practical understanding and application of data structure concepts.
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)
21 views48 pages

FDS Quality Solved Paper Endsem May 2024 PyqSPOT

The document contains an examination paper for a course on Data Structures, featuring a total of 8 questions covering various topics such as sorting algorithms (bubble sort, selection sort), searching algorithms (binary search, Fibonacci search), linked lists, and queue implementations. Each question requires detailed explanations, pseudocode, and step-by-step executions for algorithms, along with complexity analysis. The paper emphasizes practical understanding and application of data structure concepts.
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/ 48
Total No. of Questions : 8] PB3634 jorouti S.E. (Computer Engineering) (Artificial Intelligence & Data Science) FUNDAMENTALS OF DATA STRUCTURES (2019 Pattern) (Semester-II1) (210242) QS SEAT No. : [Total No. of Pages : 2 Time : 2% Hours} [Max. Marks : 70 Instructions to the cai #9 1) Attempt question Por Q2, Q3 or 04, QS or Q6, O7 or OS. 2) Figures tthe right indicate full marks. 3) Assuin®Snitable data if necessary. y Neatd ram’ must be drawn wherever necessary. 3 QI) a) Sort given array by using bubble sort method: 64,33, 25, 12, 22, 11, 90 Show Step by step execution for all the passes highlighting “swap” and “No Swap” situations. How many passes are required to sort an array of Nelements ing bubble sort? = =o 1 b) Write an algorithm to search neGhenirey Ausing binary search technique, Show stepwise searcbf KeN0 in 1, 2, 3,4,5,6,7,8,9, 10, 11. Is there any pre-processie,6f dati required before starting binary search or what i its precursor requifement? 191 RO 2) a) Enlist different search ered Write short note on 19) i) Fibonacci Search ii) Index SequentatSeaidn Vv b) Sort given array by using:sélection sort method 50, 23, 03, 18, 9, 01 i, 21, 20, 6, 40, 04. Show step by step execution of all passes. What is the best and worst exse\iie complexity of selection oe © pl 03) a) Write pseudo ede A following function using ney Linked List of integer numbers \ p>) i) Insert given value as last value in thelist. Rew diagatn of operation. i) Delete first node from the list. Draw diagrain of operation. Delete last node from the lst. Draw diag im oF dperation, b) Writeand explain node structure of OT" i) Generalized linked list © ii) Circularly Singly Linked List Draw and explain insertion of value in Circirly Singly Linked List with example. 91 PLO. Other Subjects: www.pyqspot.com Q4) a) b) Q5) a) b) 6) a) b) Q7) a) b) Q8) a) b) [6261]- Write pseudocode to perform merging of two sorted singly linked lists of integers into third list. Write complexity of it. 19) Write and explain node structure of Generalized linked list for representing multiple variable polynomial, Répresent given polynomial graphically using Generalized Labea List: Se Txy® + xz. 19) Orv WHA Write rules t6°convert Biven infix expression to postfix expression using stack. Convert exptession (A* B — (C+D * E)” (F * G/ H)) stepwise using abv rules? Where Xs - eXponential operator. 18] Explain witl’example three different types of recursiost> p ws a we OR Whai/is infix, prefix and postfix expression? Give example of each. EXplain evaluation of postfix expression with siitable example expression gad assume values for variables useg'to sole it. 18] © Write pseudo-C/C+ code to implement Stack using array with overflow and underflow conditions. 5”? 191 What are advantages offCiréula® Queue over Linear Queue using static memory allocation? Wejte pseudocode to add and remove element from Circular Queue alorg with Queue Full and Empty condition. I Draw and explain implementation of Linear Queue using Singly Linked List. Explain Add, Rempve, Queue Full and Queue Empty operations. ° 19] S OR oY oO What is Doubly Ended Queue? Draw Diagram withabelli four basic operations at appropriate places, Which two datagtrictures are combined init and how? Dy 16] g v Draw and explain Priority Queue? State any-Real lif€application. [6] Write pseudocode for Linear Queue Implen jentafion using array. [5] 41 ase Other Subjects: www.pyqspot.com QI) a) Sort given array by using bubble sort method: 64, 34, 25, 12, 22, 11, 90. Show step by step execution for all the passes highlighting “swap” and “No Swap” situations. How many passes are required to sort an array of N elements using bubble sort? Ans: Initial: 64 | 34 25 12 22 i 90 Initial unsorted array Pass 1/Step 1: 4 64 | 25 12 22 iu 90 ‘Compare 64 and 34 (Swap) Pass 2/Step 2: 34/25 64 12 22 W 90 Compare 64 and 25 (Swap) Pass 3/Step 3: ee} 12 | 64 22 i 90 Compare 64 and 12 (Swap) Pass 4/Step 4: 34 «(25 2 |2 64 iW 90 Compare 64 and 22 (Swap) Pass 5/Step 5: 34 ]25 [2 ]2 ]N |e ]90 ‘Compare 64 and 11 (Swap) Pass 6/Step 6: 34/25 12, | 22 IL 64 | 90 Compare 64 and 90 (No Swap) Sorting executed in 6 pass with 5 Swaps and 1 No swap. EX Other Subjects: www.pyqspot.com Q1) b) Write an algorithm to search an element in array A using binary search technique. Show stepwise search of Key 10 in 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11. Is there any pre-processing of data required before starting binary search or what is its precursor requirement? Ans: Algorithm for Binary Search The binary search algorithm works by dividing the search interval in half. The precursor requirement for binary search is a sorted array. Algorithm: 1. Input: A sorted array A of size n and the element to search, Key. 2. Initialize: o Low=0 (first index of the array) o High =n-I (last index of the array) 3. Repeat until Low < High: o Compute Mid= |(Low + High)/2]. o Compare A[Mid] with Key: + IfA[Mid]—Key: Return the index Mid\text {Mid} + IfA[Mid]Key: Set High=Mid-1. 4. Ifthe element is not found, return -1. Stepwise Search for Key 10 in Array [1,2,3,4,5,6,7,8.9,10,11] Initial Array: [1,2,3,4,5,6,7,8,9,10,11] Step 1: + Low=0, High=10 = [(O+10y2|=5 + A[Mid] =6 + Key (10) > 6, so update Low = Mid+1=6. * Mi EX Other Subjects: www.pyqspot.com Step 2: + Low=6, High=10 + Mid =((6+10)2|=8 + A[Mid]=9 ‘+ Key (10) > 9, so update Low = Mid+1=9. + Low=9, High=10 + Mid=[(9+10)2]=9 + A[Mid] = 10 + Key (10)== A., Found the key at index 9. Preprocessing Requirement * Sorted Array: Binary search requires the input array to be sorted in ascending or descending order. If the array is not sorted, you must sort it first, which takes O(n log n). Time Complexity 1. Best Case: O(1) (Key found in the first comparison). 2. Average and Worst Case: O (log n) (ach step halves the search space). Space Complexity + (1), as binary search uses constant space. EX Other Subjects: www.pyqspot.com Q2) a) Enlist different searching methods. Write short note on i) Fibonacci Search Index Sequential Search Ans: Different Searching Methods 1. Linear Search: Sequentially checks each element of the array until the desired element is found or the end of the array is reached. 2. Binary Search: Divides the sorted array into halves and searches in one half based on the middle clement. 3. Fibonacci Search: Utilizes Fibonacci numbers to divide the array for searching. 4, Jump Search: Skips a fixed number of elements (jump size) to locate the possible position, then performs a linear search, 5. Exponential Search: Starts with a small range and expands it exponentially until the desired range is found, then applies binary search. 6. Interpolation Search: Estimates the position of the key i a uniform distribution of data, the array based on its value, assuming 7. Index Sequential Search: Combines the advantages of sequential and indexed search for efficiency. i) Fibonacci Search + Definition: Fibonacci Search is an efficient searching algorithm for sorted arrays that uses the Fibonacci sequence to divide the array into sections. + Working: 1. Identify the smallest Fibonacci number FFF that is greater than or equal to the size of the array n, 2. Divide the array into sections using Fibonacci indices Fk~2 and Fk1. 3. Compare the element at the computed index with the key: + [fequal, return the index. + Ifthe key is smaller, search in the left subarray. + Ifthe key is larger, search in the right subarray. 4, Repeat until the key is found or the array is fully traversed. EX Other Subjects: www.pyqspot.com + Advantages: © Effective for large sorted datasets. © Reduces the search range similar to binary search but avoids direct computation of the midpoint. co Requires a sorted array. © Slightly more complex than binary search due to Fibonacci number computation. ii) Index Sequential Search + Definition: Index Sequential Search is a combination of sequential search and indexing. It ivides the array into blocks and creates an index table with key pointers for efficient searching. + Working: 1. Divide the array into fixed-size blocks. 2. Create an index table containing the largest element of each block and pointers to the corresponding block. 3. Search the index table to find the block that may contain the desired key. 4, Perform a sequential search within the identified block. + Advantages: © Faster than pure sequential search for large datasets. © Efficient for datasets where updates are infrequent. + Limitations: © Requires additional memory for the index table. © Notas fast as binary search for sorted arrays. EX Other Subjects: www.pyqspot.com Q2) b) Sort given array by using selection sort method 50, 23, 03, 18, 9, 01, 70, 21, 20, 6, 40, 04. Show step by step execution of all passes. What is the best and worst case time complexity of selection sort? Ans: Initial Array: 30] 23] 3 [18] 9] 1 [70] 21] 20] 6 [40] 4 Pass 1/Step 1: © Find the smallest element: 01 © Swap 50 with O1. © After Pass 1: Pass 2/Step 2: * Find the smallest element in the unsorted part: 03 © Swap 23 with 3. © After Pass 2: 1 | 3 [23] 18] 9 150] 70] 21] 20] 6 [40] 4 Pass 3/Step 3: Find the smallest element in the unsorted part: 04 Swap 23 with 04. After Pass: Pass 4/Step 4: Find the smallest element in the unsorted part: 06 Swap 18 with 06. © After Pass: EX Other Subjects: www.pyqspot.com Pass 5/Step 5: Find the smallest element in the unsorted part: 09 ‘© Swap 9 with itself (no change). © After Pass 5: 113] 4] 6] 9 [50] 70] 21 [20] 18] 40 | 23 Pass 6/Step 6: Find the smallest element in the unsorted part: 18 Swap 50 with 18. © After Pass 6: 1]3]4] 6] 9 | 18] 70] 21 | 20] 50] 40] 23 Pass 7/Step 7: Find the smallest element in the unsorted part: 20 Swap 70 with 20. After Pass 7: 1]3]4] 6] 9 | 18] 20] 21] 70] 50] 40] 23 Pass 8/Step 8: Find the smallest element in the unsorted part: 21 Swap 21 with itself (no change). © After Pass 8: 1] 3]4] 6] 9 | 18] 20] 21 | 70] 50] 40] 23 Pass 9/Step 9: ind the smallest element in the unsorted part: 23 Swap 70 with 23. After Pass 9: Pass 10/Step 10: Find the smallest element in the unsorted part: 40 © Swap 50 with 40, © After Pass 10: EX Other Subjects: www.pyqspot.com Pass 11/Step 11: Only one element left, so no swaps required. Final Array: 11374] 6] 9 | 18] 2021 [23] 40] 50] 70 Other Subjects: www.pyqspot.com Q3) a) Write pseudo code for following function using Doubly Linked List of integer numbers i) Insert given value as last value in the list. Draw diagram of operation. Delete first node from the i t. Draw diagram of operation. ) Delete last node from the list. Draw diagram of operation. Ans: i) Insert Given Value as Last Value in the List 1. Input: The value val to be inserted. 2. Create a New Node: © Allocate memory for a new node newNode. © Set newNode.data = val. Set newNode.nex = NULL. 3. Ifthe List is Empty: © Set head = newNode (Make the new node the head). © Set newNode.prev = NULL. © Traverse the list to find the last node tail (where tail.next = NULL). Set tail.next = newNode. © Set newNode.prev = tail. 5. Output: Updated doubly linked list. Diagram of Operation Before Insertion: Head — 10= 202 30 = NULL. After Inserting 40: Head — 1022 202 30 = 40 2 NULL ii) Delete First Node from the List 1. Input: A doubly linked list. 2. Ifthe List is Empty: © Print "List is empty" and exit. EX Other Subjects: www.pyqspot.com Else: © Store the current head node in temp. © Set head = head.next. o Ifhead # NULL, set head.prev = NULL. Free memory allocated for temp. 3. Output: Updated doubly linked list. Diagram of Operation Before Deletion: Head — 10 # 20 2 30 @ NULL After Deleting First Node: Head —+ 20 = 30 @ NULL. Delete Last Node from the List 1. Input: A doubly linked list. 2. Ifthe List is Empty: © Print "List is empty" and exit. 3. Else: ©. Traverse the list to find the last node tail (where tail.next= NULL). © Set tail.prev.next = NULL (Detach the last node). © Free memory allocated for tail. 4, If the List Has Only One Node: © Set head = NULL. 5. Output: Updated doubly linked list. Diagram of Operation Before Deletion: Head — 10 = 20 = 30 @ NULL After Deleting Last Node: Head — 10 = 20 NULL. EX Other Subjects: www.pyqspot.com Q3) b) Write and explain node structure of i) Generalized linked list. ii) Cireularly Singly Linked List. Draw and explain insertion of value in Circulai ‘ingly Linked List with example. Ans: i) Generalized Linked List A Generalized Linked List (GLL) is a collection of nodes where each node can either store: + A data element (like an integer, string, or any other type). + A pointer to another list (a sublist). Each node in a GLL typically consists of two parts: 1. Data/Pointer: Holds the actual data or a pointer to a sublist. 2. Next Pointer: Points to the next node in the list. Structure of a Generalized Linked List Node struct Node { Data/Pointer: Stores data or points to another list. Next: Pointer to the next node in the list. } Example of Generalized Linked List Consider the li : [10, [20, 30}, 40] + The first node contains 10 and a pointer to the second node. * The second node points to a sublist [20, 30] The third node contains 40, ii) Circular Singly Linked List. A Circular Singly Linked List is a type of linked list where: 1. The last node points back to the first node, forming a circle. 2. Each node contains o Data: Holds the value. BX Other Subjects: www.pygspot.com © Next Pointer: Points to the next node. Structure of a Circular Singly Linked List Node struct Node { Data: Stores the value of the node. Next: Pointer to the next node in the list. i Example of Circular Singly Linked List List: 10 20 — 30 — 10 (head) Insertion in a Circular Singly Linked List Steps for Insertion (At the End): 1. Create a New Node: © Allocate memory for the new node. © Set newNode.data = value. © Set newNode.next = NULL. 2. Ifthe List is Empty: © Set head = newNode. © Set newNode.next = newNode (Point to itself). 3. Else: co Traverse the list to find the last node (the node whose next points to head). © Set lastNode.next = newNode. © Set newNode.next = head. 4. Return the Updated List. Example: Inserting 40 into Circular Singly Linked List Initial List: 10 > 20 + 30 + 10 (head) Step 1: Create a new node for 40. EX Other Subjects: www.pyqspot.com newNode.data = 40 newNode.next = NULL Step 2: Traverse to the last node (30). + Set 30.next = newNode. Step 3: Link the new node back to the head. + Set newNode.next = head. Resulting List: 10 > 20 — 30 + 40 — 10 (head) Diagram Before Insertion: [10] — [20] + [30] — (points back to head — [10}) After Insertion: [10] —+ [20] — [30] — [40] — (points back to head — [10)) EX Other Subjects: www.pyqspot.com Q4) a) Write pseudocode to perform merging of two sorted sin; Write complexity of it. Ans: Pseudocode 1. Input: Two sorted singly linked lists, LI and L2. 2. Output: A merged sorted singly linked list, L3. Function MergeSortedLists(L1, L2): Initialize L3 as an empty linked list Initialize pointers p1 = head of L1, p2 = head of L2 Initialize tail = NULL for L3 (used to build the list) While p1 is not NULL and p2 is not NULL: If pl.data <= p2.data: Create a new node with value p1.data Add this node to the end of L3 Move pl to the next node in Li Else: Create a new node with value p2.data Add this node to the end of L3 Move p? to the next node in L2 While p! is not NULL: # Remaining nodes in LI Create a new node with value p1.data Add this node to the end of L3 Move pl! to the next node in L1 ked lists of integers into third list. BX Other Subjects: www.pygspot.com While p2 is not NULL: # Remaining nodes in L2 Create a new node with value p2.data Add this node to the end of L3 Move p2 to the next node in L2 Return head of L3 Step-by-Step Example Let: 6 LIF1o345 © 1224456 1, Compare 1 (from L1) and 2 (from L2): o Add 1toL3:L3 o Move pl to 3. 2. Compare 3 (from L1) and 2 (from L2): © Add 2 to L3: L3=142 © Move p2to4. 3. Repeat comparisons and add smaller elements to L3: Final L3=1+2-3-4—5-6. ‘Time Complexity 1. Merging Process: © Bach node from L1 and L2 is visited exactly once. o Total nodes = m+n , where m is the size of L1 and n is the size of L2. Time Complexity: O(m#n) L3 is created, so O(m*n) additional space is required. © Ifin-place merging is done (using the original nodes of L1 and L2), space complexity becomes O(1). EX Other Subjects: www.pyqspot.com Q4) b) Write and explain node structure of Generalized linked list for representing multiple variable polynomial, Represent given polynomial graphically using Generalized Linked List: 5x’ + 7xy*t I1xz. Ans: Generalized Linked List (GLL) A Generalized Linked List (GLL) is a hierarchical linked structure used to represent complex data, such as polynomials with multiple variables. Unlike a standard linked list that stores linear data, a GLL can store: 1. Atomic elements (simple data like coefficients). 2. References to other lists (to represent relationships or structures). In the case of multivariable polynomials, each term can be represented as a node in the list, with sublists to store variables, their powers, and coefficients. Node Structure for a Polynomial GLL Bach node has: 1. Pointer to data (coefficient or variable information). 2. Pointer to the next node (linking terms together). 3. Pointer to a sublist (representing variables and powers of the current term). For a polynomial 5x” + 7xy® I1xz: + First level: Represents the terms. + Second level: Represents variables and powers for each term. Representation of 5x” + 7xy®+ 11xz. 1. Term breakdown: + 5x7: Coefficient = 5, Variable x, Power = 7. + Txy®: Coefficient = 7, Variables xy, Powers 1,6. + 11xz: Coefficient = 11, Variables xz, Powers 1,1 EX Other Subjects: www.pyqspot.com 3. Graphical Representation of the GLL: Oly Advantages of Generalized Linked Lists (GLL): + Representation of Hierarchical/Nested Data: Can store both atomic data and sublists, ideal for trees, ‘graphs, and recursive structures. + Dynamic Memory Allocation: ficient memory use, grows and shrinks based on data needs. + Recursive Data Representation: Suitable for recursive structures and operations (e.g., trees, graphs). + Efficient Insertion/Deletion: insert and delete elements in constant 1e (O(1)). + Natural for Complex Algorithms: Simplifies algorithms dealing with non-linear data structures. + Versatility: Can store mixed data types (e.g., numbers, strings, sublists). + Custom Data Types: Supports user-defined data types and complex objects. Use Cases: + Symbolic computation (e.g., LISP) + Representing hierarchical or nested structures (e.g., trees, XML) + Graph-based data structures EX Other Subjects: www.pyqspot.com Q5) a) Write rules to convert given infix expression to postfix expression using stack. Convert expression (A* B- (C+D * E)* (F* G/H) stepwise using above rules. Where ” is - exponential operator. Ans: Rules to Convert Infix Expression to Postfix Expression Using Stack The process of converting an infix expression (where operators are between operands) to postfix (also known as Reverse Polish Notation or RPN, where operators follow their operands) using a stack involves the following steps: 2, 5. 6. c Operands (variables and constants) are added directly to the output (postfix expression). Left Parenthesis (: Push it onto the stack to indicate the start of a subexpression, Right Parenthesis ): Pop operators from the stack to the output until a left parenthesis ( is encountered. Discard the left parenthesis. Operators: Pop operators from the stack to the output while the operator at the top of the stack has greater than or equal precedence (depending on the associativity) compared to the current operator. Then push the current operator onto the stack. Operator Precedence: © Exponentiation (‘) has the highest precedence. © Multiplication (*) and Division (/) have medium precedence. © Addition (+) and Subtraction (-) have the lowest precedence. Operator Associativity: co Exponentiation (*) is right-associative (right to left). © Other operators (*, /, +,-) are left-associative (ler to right). At the end of the expression, pop any remaining operators from the stack to the output. Stepwise Conversion of Infix Expression to Postfix Given expression: (A * B - (C+D * E)*(F *G/H)) BX Other Subjects: www.pyqspot.com Step 1: Initialize + Infix: (A* B-(C+D*E)*(F*G/H)) + Postfix: (Empty) + Stack: (Empty) Step 2: Read first token: ( + Postfix: (Empty) © Stack: ( Step 3: Read token: A + Postfix: A © Stack: ( Step 4: Read token: * + Postfix: A + Stack: (,* Step 5: Read token: B + Postfix: AB © Stack: (,* Step 6: Read token: - + Postfix: AB * * Stack: ( (pop * because - has lower precedence), ~ Step 7: Read token: ( + Postfix: AB * # Stack: (,-,( Step 8: Read token: C EX Other Subjects: www.pyqspot.com * Postfix: AB *C © Stack: (,-, ( Step 9: Read token: + + Postfix: AB *C * Stack: Step 10: Read token: D + Postfix: AB*CD + Stack: (=, 6% Step 11: Read token: * + Postfix: AB*CD © Stack: (, -, , +, * (push * since it has higher precedence than +) Step 12: Read token: E + Postfix: AB* CDE # Stack: (5-64, * Step 13: Read token: ) + Postfix: AB*CDE*+ * Stack: (,- (pop + and * until ( is encountered) Step 14: Read token: + Postfix: AB*CDE*+ * Stack: (,-, * (push * since it has higher precedence than -) Step 15: Read token: ( + Postfix:AB*CDE*+ # Stack: (,-,%,( EX Other Subjects: www.pyqspot.com Step 16: Read token: F + Postfix: AB*CDE*+F # Stack: (,-,%,( Step 17: Read token: * © Postfix:AB*CDE*+F # Stack: 6-6" Step 18: Read token: G © Postfix:AB*CDE*+FG # Stack: (=. * Step 19: Read token: / * Postfix:AB*CDE*+FG* + Stack: (,-, (/ (push / since it has higher precedence than *) Step 20: Read token: H © Postfix:AB*CDE*+FG*H # Stack: (=, G/ Step 21: Read token: ) + Postfix: AB*CDE*+FG*H/* + Stack: (,-, (pop / and * until (is encountered) Step 22: End of Expression © Postfix:AB*CDE*+FG*H/**- + Stack: (Empty) (pop remaining -) Final Postfix Expression: AB*CDE*+FG*H/*- EX Other Subjects: www.pyqspot.com Step | Stack I] Stack 2 | Stack 3 | Stack 4] Stack 5 | Stack 6] Stack 7 | Stack 1 {¢ 2 TC 7 Ee * a ra * a B 5 IC x B * 6 A B * . cK A B : = C 8 TC A B * = ( c CW A B z = C c wo {¢ a B + = C a nm {¢ a B * = C c mR {C a B * - C os B {C x B * - C c m {C x B * - C ic is | ¢ A B * - C c 16 | C A B . = C c a7 {C A B * = ( c is | ( A B + = C ic wo | ¢ A B * = C c 2 10 a B : = C Gc a TC a B * - C c 2 a B * : € + EX Other Subjects: www.pyqspot.com Q5) b) Explain with example three Ans: ifferent types of recursion. Recursion is a technique in programming where a function calls itself to solve a problem, In general, recursion can be classified into three primary types: Tail Recursion, Head Recursion, and Tree Recursion. Let’s explain each type with more detail and provide C++ examples. 1. Tail Recursion In tail recursion, the recursive call is the last operation performed in the function. This allows for the possibility of optimization by the compiler, called tail call optimization (TCO), which reuses the stack frame, leading to more efficient memory usage Example of Tail Recursion: Calculating the factorial of a number using tail recursion. #include using namespace std; int factorialTail(int n, int accumulator = 1) { if(n<=1) return accumulator; else return factorialTail(n - 1, n * accumulator); // recursive call is the last action } int main() { int number = 5; cout << "Factorial of " << number <<" is: " << factorial Tail(number) << endl; return 0; 4 Explanation: + The function factorialTail computes the factorial of n using an accumulator that stores the intermediate results. + The recursive call factorialTail(n - 1, n * accumulator) is the last operation. * No further computations are done after the recursive call, making this tail recursion. BX Other Subjects: www.pygspot.com 2, Head Recursion In head recursion, the recursive call occurs before any operation is done in the function. This means that the recursive function keeps calling itself until the base case is reached, and the operations (such as multiplication or addition) are performed after returning from the recursion. Example of Head Recursion: Calculating the factorial of a number using head recursion. #include using namespace std; int factorialHead(int n) { if(n<=1) return 1; else return n * factorialHead(n - 1); // recursive call is made before multip! int main { int number= 5; cout << "Factorial of" << number <<" is: " << factorialHead(number) << endl; return 0; i Explanation: + The function factorialHead calls itself first (factorialHead(n - 1)) and then multiplies n by the result of that recursive call. + The recursion happens at the "head" of the function, and the multiplication is done after the recursive call completes. BX Other Subjects: www.pygspot.com 3. Tree Recursion In tree recursion, the function makes multiple recursive calls at each level. These calls "branch out" into two or more recursive calls, forming a tree-like structure of function calls. This type of recursion can result in exponential growth in the number of calls and may not be as efficient in terms of time complexity. Example of Tree Recursion: Calculating the Fibonacei series using tree recursion. #include using namespace std; int fibonacei(int n) { if(a<=1) return ny else return fibonacci(n - 1) + fibonacei(n - 2); // two recursive calls for each number int main { int number = 5; cout << "Fibonacci of " << number <<" is: " << fibonacci(number) << endl; return 0; } Explanation: + The function fibonacci calls itself twice: once for fibonacci(n - 1) and once for fibonacei(n - 2), This creates a tree-like structure of recursive calls. + For fibonacei(5), the funetion will call fibonacei(4) and fibonacei(3), and each of those will again make two more calls, leading to exponential growth in the number of calls. + This type of recursion leads to redundant calculations and is inefficient for large values of n. BX Other Subjects: www.pygspot.com 6) a) What is infix, prefix and postfix expression? Give example of each. Explain evaluation of postfix expression with suitable example expression and assume values for variables used to solve it. Ans: Infix, Prefix, and Postfix Expressions In mathematics and programming, expressions represent arithmetic calculations. Different notations are used to write these expressions: infix, prefix, and postfix. These are different ways to write arithmetic expressions, and each has its own rules for evaluating the order of operations. 1. Infix Expression + Infix notation is the standard arithmetic notation that we typically use. In this notation, the operators are placed between the operands. + Example: * A+B (A+B)*C * (A+B)*(C-D) Order of operations (precedence) in infix expressions is determined by parentheses first, followed by multiplication, division, and then addition and subtraction. 2. Prefix Expression + Prefix notation, also known as Polish notation, places the operator before the operands. + There is no need for parentheses in prefix notation, as the order of operations is implied by the position of the operator. + Example: * +AB ° *+ABC © -+AB*CD In prefix notation, you always evaluate from right to left, starting with the operator. 3. Postfix Expression Postfix notation, also known as Reverse Polish notation (RPN), places the operator after the operands, Like prefix notation, parentheses are not needed, and the order of operations is determined by the position of operators. BX Other Subjects: www.pygspot.com + Example: © ABE AB+C* AB+CD*- In postfix notation, you evaluate from left to right by using a stack to store operands until the operator is encountered, Evaluation of Postfix Expression To evaluate a postfix expression, you can use a stack. Here's the general algorithm: 1. Scan the expression from left to right. 2. Push operands (numbers or variables) onto the stack 3. When an operator is encountered: Pop two operands from the stack. + Perform the operation using these two operands. * Push the result back onto the stack. 4, After processing all the characters, the result will be the only value left in the stack. Example of Postfix Evalu: on Let's evaluate the following postfix expression: 53+4*6- Step 1: Define Values + LetA=5,B=3,C=4,andD=6. Step-by-Step Evaluation: 1. Initial expression: 53 +4 *6- 2. Scan the first token (5): Operand — Push 5 onto the stack. Stack: [5] 3. Sean the next token (3): Operand — Push 3 onto the stack. Stack: [5, 3] 4, Scan the next token (+): Operator +> Pop two operands (5 and 3) from the stack. Perform the operation: 5 + 3 = 8. Push the result (8) onto the stack. Stack: [8] 5. Scan the next token (4): Operand —> Push 4 onto the stack. Stack: [8,4] 6. Sean the next token (*): Operator — Pop two operands (8 and 4) from the stack. Perform the operation: 8 * 4 = 32 BX Other Subjects: www.pygspot.com 9, Push the result (32) onto the stack. Stack: [32] Scan the next token (6): Operand —> Push 6 onto the stack. Stack: [32, 6] Scan the next token (-): Operator — Pop two operands (32 and 6) from the stack. Perform the operation: 32 - 6 = 26. Push the result (26) onto the stack. Stack: [26] Final Result: After processing all the tokens, the only value left in the stack is 26, which is the result of the postfix expression. CH Code for Postfix Evaluation #include #include #include #include using namespace std; int evaluatePostfix(string expression) { stack s; stringstream ss(expression); string token; while (6s >> token) { if (isdigit(token[0)) { //1f the token is a number, push it onto the stack s.push(stoi(token)); } else { //If the token is an operator, pop two elements and perform the operation top(); s-pop()s top(); s.pop(): int operand2 int operand! = if (token BX Other Subjects: www.pygspot.com s.push(operandl + operand2); pit s.push(operandl - operand2); } else if (token = "*") { } else if (token = s.push(operandl * operand2); "yt s.push(operandl / operand2); } else if (token Ji The final result will be the only element left in the stack return s.top(); } int mainQ) { string postfix ="53+4*6-"; cout << "Result of postfix expression: " << evaluatePostfix(postfix) << endl; return 0; } Explanation of Code: + Stack: A stack is used to store operands during evaluation, + Stringstream: It is used to split the input expression into tokens (operands or operators). + Evaluation: The program checks if each token is an operand (number) or operator. If it's an operand, it's pushed onto the stack. If i's an operator, it pops two operands from the stacl performs the operation, and pushes the result back onto the stack. Output: Result of postfix expression: 26 BX Other Subjects: www.pygspot.com Q6) b) Write pseudo-C/C-++ code to implement stack using array with overflow and underflow conditions. Ans: Stack Structure + Stack Overflow occurs when trying to push an element onto a full stack. + Stack Underflow occurs when trying to pop an element from an empty stack include using namespace std; #define MAX 5 / Define the maximum size of the stack class Stack { private: int an{MAX];_// Array to store stack elements inttop; _// Index of the top element in the stack publi J} Constructor to initialize stack Stack() { top=-1; // Stack is empty initially /} Push operation to add an element to the stack void push(int value) { if (top = MAX - 1) { // Check for stack overflow cout << "Stack Overflow: Unable to push " << value << endl; }else { topt+; //Inerement top index arr{top]= value; // Push value to the stack cout << "Pushed " << value <<" to stack." << endl; 1) Pop operation to remove an element from the stack BX Other Subjects: www.pygspot.com int pop) { if (top cout << "Stack Underflow: No elements to pop.” << endl; 1) { // Check for stack underflow return -1; // Return a sentinel value indicating underflow. }else { int poppedValue = arr{top]; // Get the top element top-; // Decrement top index cout << "Popped " << poppedValue <<" from stack." << endl; return poppedValue; // Return the popped value /) Function to check the top element without removing it int peek) { if (top =-1) { cout << "Stack is empty." << endl; return -1; else { return ar[top]; // Return the top clement. /} Function to check if the stack is empty bool isEmpty() { return top —-1; // Return true if stack is empty // Function to display the elements of the stack void display() { if top =-1) £ cout << "Stack is empty." << endl; yelse { BX Other Subjects: www.pygspot.com cout << "Stack elements: "; for (int i= 0; i <= top; it) { cout << arr{i] <<"; // Print each element 5 cout << endl; } h int main() { Stack s; // Test push operation with overflow condition s.push(10); // Push 10 to stack s.push(20); // Push 20 to stack sipush(30); // Push 30 to stack s.push(40); // Push 40 to stack s.push(50); // Push 50 to stack s:push(60); //'Stack overflow condition // Display the stack s.display(); // Test pop operation with underflow condition sop; // Pop 50 from stack s.pop(); // Pop 40 from stack s:pop(); _// Pop 30 from stack s.pop(); // Pop 20 from stack s.pop(); // Pop 10 from stack spop(); // Stack underflow condition // Display the stack after popping elements sdisplay(; return 0; BX Other Subjects: www.pygspot.com Q7) a) What are advantages of Circular Queue over Linear Queue using static memory allocation? Write pseudocode to add and remove element from Circular Queue along with Queue Full and Empty condition. Ans: Advantages of Circular Queue over Linear Queue Using Static Memory Allocation Ina Linear Queue, when elements are removed, there can be wasted space at the front of the queue (because the front index increases while the rear remains unchanged), even if there is space available at the end, This phenomenon is called queue underutilization. On the other hand, a Cireular Queue solves this issue by reusing the space once elements are removed. When the rear pointer reaches the end of the queue, it wraps around to the beginning, effectively utilizing all the available memory. Advantages of Circular Queue over Linear Queue: 1. Efficient Memory Uti mn: In a circular queue, when the rear pointer reaches the end of the queue, it wraps around to the beginning of the array, allowing for efficient use of space. In a linear queue, there can be unused space even when there is space available, 2. No Wasted Space: In a linear queue, once elements are dequeued, the front pointer keeps moving forward, and if new elements are added after the front moves, there will be unused space in the beginning. In a circular queue, when the rear reaches the end of the array, it wraps around to the beginning, thus filling the empty spots without wasting space. 3. Better Performance: Circular queues allow for better use of the fixed memory allocated for the queue, and the enqueue and dequeue operations can be done without having to shift elements as in the case of a linear queue. 4, Constant Time Operations: In a circular queue, both enqueue and dequeue operations are done in constant time, O(1), without any shifts of elements. Circular Queue Operations with Pseudocode Ina circular queue, we maintain two pointers: + front: It points to the first element of the queue (or -1 if the queue is empty). + rear: It points to the last element of the queue (or -1 if the queue is empty). The queue full condition occurs when (rear + 1) % size = front, and the queue empty condition oceurs when front == Pseudocode to Add and Remove Elements from Cireular Queue Circular Queue Representation + Size of the Queue: size + Front: Points to the front element of the queue, initialized to -1 (empty queue). + Rear: Points to the last element of the queue, initialized to -1 (empty queue). + Array: queue[size], holds the elements, BX Other Subjects: www.pygspot.com 1, Enqueue Operation (Adding an element) ENQUEUE(queue, size, front, rear, value): IF (rear + 1) % size = front: PRINT "Queue is full” ELSE: IF front = : front = 0) rear = (rear + 1) % size queuefrear] = value PRINT "Enqueued ", value 2.Dequeue Operation (Removing an element) DEQUEUE(queue, size, front, rear): IF front = -1: PRINT "Queue is empty" ELSE: value = queue front] IF front == rear: front = rear =-1 ELSE: front = (front + 1) % size PRINT "Dequeued ", value 3. Check if the Queue is Empty 1S_EMPTY (front): IF front = RETURN TRUE ELSE: RETURN FALSE END IS_EMPTY 4. Cheek if the Queue is Full IS_FULL(front, rear, size): IF (rear + 1) % size = front: RETURN TRUE ELSE: RETURN FALSE END IS_FULL BX Other Subjects: www.pygspot.com C+ Code to Implement Circular Queue include using namespace std; ‘define SIZE 5 class CircularQueue { private: int arr{SIZE], front, rear; publi CircularQueue() = front(-1), rear(-1) {} bool isEmpty() { return front = -1; } bool isFull() { return (rear + 1) % SIZE = front; } void enqueue(int value) { if (isFull) cout << "Queue is full"; else { if (front = -1) front = rear = (rear + 1) % SIZE; arrfrear] = value; cout << "Enqueued " << value << endl; int dequeue() { if (isEmpty()) { cout << "Queue is empty\n"; return -1; } int value = arr{front]; if (front = rear) front = rear else front = (front + 1) % SIZE; cout << "Dequeued " << value << endl return value; BX Other Subjects: www.pygspot.com void display() impty()) cout << "Queue is empty\n"; else { int i= front; cout << "Queue: "; while (i != rear) cout << arr[i] <<" ",i= (i+ 1) % SIZE; cout << arr{rear] << endl; H int main() { CircularQueue q; qenqueue(10); q.enqueue(20); q.enqueue(30); q.enqueue(40); q.enqueue(50); qeenqueue(60); 4.display(); qdequeue(); g.dequeue(); q.dequeue(); q.display(): qenqueue(60); q.enqueue(70); q.display(); Explanation: 1. Constructor initializes front and rear to -1. isEmpty( and isFull check the queue's status. enqueue(): Adds an element if the queue is not full. Wraps the rear pointer using modulo. a eR dequeue(): Removes an element if the queue is not empty. Updates the front pointer using modulo. 5. display(): Displays the queue’s elements in the correct order, using a circular approach. EX Other Subjects: www.pyqspot.com Q7) b) Draw and explain implementation of Linear Queue using Singly Linked List. Explain Add, Remove, Queue Full and Queue Empty operations. Ans: Linear Queue using Singly Linked List A Linear Queue using a Singly Linked List is an implementation of a queue where elements are added at the end (rear) and removed from the front, just like a traditional queue, but using a linked list for dynamic memory management. Unlike a static array-based queue, a linked list can grow and shrink dynamically without the need for resizing, Queue Operations: + Add (Enqueue): Insert an element at the rear (end) of the queue. + Remove (Dequeue): Remove an element from the front of the queue. * Queue Full: In a dynamically allocated queue (using linked lists), this condition doesn’t exist unless system memory is exhausted. * Queue Empty: This condition occurs when there are no elements in the queue (front NULL). Structure: Each node in the linked list consists of: + data: Stores the value of the element. + next: A pointer to the next node in the queue, Queue Structure (Linked List Representation): Front—»[Data_[Next—}—»[ Data [Next }—» [Data [Next Js nulle—Rear © Front: Points to the first node in the queue (where elements are dequeued). © Rear: Points to the last node in the queue (where elements are enqueued). © NULL: Indicates the end of the queue, Implementation of Linear Queue using Singly Linked List (C++) #include using namespace std; class Node { publi int data; BX Other Subjects: www.pygspot.com Node® next Node(int value) : data(value), next(NULL) {} % class Queue { private: Node *front, *rear; put Queue() : front(NULL), rear(NULL) {} bool istimpty() { etum Mont; } ‘void engueue(int value) { Node* newNode = new Node( value); if (isEmpty() front = rear = newNode; else { rear->ne newNode; rear = newNode: } ‘cout << "Enqueued: " << value << endl; void dequeue() { if (isEmpty() { cout << "Queue is empty.” << endl; return; } Node* temp = front; ‘cout << "Dequeued: " << front->data << endl; front = front->next; if (front) rear = NULL; delete temp; void display() { if (isEmpty) { cout << "Queue is empty.” << endl; return; } Node* temp = front; cout << "Queue: ‘while (temp) { cout << temp->data <<" temp = temp->next; } cout << endl; EX Other Subjects: www.pyqspot.com int main() { Queue g; next = newNode; rear = newNode; EX Other Subjects: www.pyqspot.com 2. Remove (Dequeue) Operation: «Steps: © Ifthe queue is empty (ie., front is NULL), print a message indicating that the queue is empty and cannot perform the dequeue operation. © Ifthe queue is not empty, remove the node from the front by setting the front pointer to the next node in the queue. o Ifthe queue becomes empty after dequeuing, set the rear to NULL, © Free the memory occupied by the removed node. + Code: void dequeue() { if (isEmpty()) { cout << "Queue is empty." << endl; return; } Node* temp = front; front = front->next; if (front = NULL) rear = NULL; delete temp; } - Queue Full Condi + Ina llinked list-based queue, there is no predefined size limitation unless the system memory exhausted. Therefore, the queue never becomes "full" in the traditional sense unless the system runs out of memory. 4, Queue Empty Condition: + The queue is empty if the front pointer is NULL. This condition is checked before both enqueue and dequeue operations to ensure that the queue is not empty before performing dequeue or display operations. + Code: bool isEmpty() { return front = NULL; Other Subjects: www.pygspot.com Q8) a) What is Doubly Ended Queue? Draw Diagram with labelling four basic operations at appropriate places. Which two data structures are combined in it and how? Ans: Doubly Ended Queue (Deque) A Doubly Ended Queue, often abbreviated as Deque, is a linear data structure that allows insertion and deletion of elements from both ends, i.c., from the front and the rear. Key Operations of a Deque: 1. Insert Front (enqueueFront): Adds an element at the front of the deque. Insert Rear (enqueueRear): Adds an element at the rear of the deque. Delete Front (dequeueFront): Removes an element from the front of the deque. RYN Delete Rear (dequeueRear): Removes an clement from the rear of the deque. Deque Operations Diagram: ‘ADD ELEMENT AT REAR ‘ADD ELEMNET AT FRONT TA near oe [=| =[»[»[*]=] 4] J REMOVE ELEMENT FROM REAR REMOVE ELEMENT FROM FRONT Data Structures Combined in Deque: A Deque is typically implemented by combining a doubly linked list and a linear queue. 1. Doubly Linked List: © The deque uses a doubly linked list to allow insertion and deletion from both ends efficiently. Each node in the doubly linked list contains pointers to both the previous and next nodes, allowing traversal in both directions. © Insertion and deletion at both ends (front and rear) can be performed in constant time oO”). 2. Linear Queue: © The queue operations (FIFO - First In, First Out) are enhanced with the ability to operate at both ends. © This allows the deque to function like a queue (for insertion/removal at the rear) and like a stack (for insertion/removal at the front). BX Other Subjects: www.pygspot.com Deque Example: 1. Insert Fro dd an element at the front of the deque. 2. Insert Rear: Add an element at the rear of the deque. 3. Delete Front: Remove an element from the front. 4. Delete Rear: Remove an element from the rear. By combining the features of both a queue and a stack, a deque allows greater flexibility in managing elements, making it a versatile data structure for many applications where operations need to be performed at both ends of the collection. Q8) b) Draw and explain Priority Queue? State any real life application, Ans: Priority Queue A Priority Queue is a data structure similar to a regular queue but with an additional feature: each element in a priority queue is assigned a priority. In a priority queue, clements are dequeued in order of their priority rather than their order of arrival. The highest priority elements are dequeued first, regardless of when they were added to the queue. Operations of a Priority Queue + Insert (Enqueue): Add an element to the priority queue with a specified priority. + Delete (Dequeue): Remove the element with the highest priority (ie., the element at the front of the queue), + Peek: View the element with the highest priority without removing it. Types of Priority Queues: 1. Min Priori Queue: The element with the lowest priority is dequeued first. 2. Max Priority Queue: The element with the highest priority is dequeued first. gram: highest pronty lowest pinty highest pronty lowest pionty iment loment omont Slment t ‘ + \ ee oe rmin-priority queue ‘max-prioty queue BX Other Subjects: www.pyqspot.com In this diagram, the element at the front of the queue has the highest priority. When a new element is added, it is inserted based on its priority. In the case of a max priority queue, the element with the highest priority will always be at the front. Working of Priority Queue: 1. Insert: When an element is inserted into the queue, it is placed in the appropriate position based on its priority (higher priority elements move toward the front). 2. Delete: The element with the highest priority is removed from the front of the queue 3. Peek: The element at the front can be viewed to see which element has the highest priority without removing it. Real-l fe Applications of Priority Queue: 1, Job Scheduling in Operating Systems: Example: In an operating system, the CPU scheduler uses a priority queue to manage processes. Processes with higher priority are executed first 2. Dijkstra's Algorithm for Shortest Path: co Example: In graph algorithms like Dijkstra's algorithm, a priority queue is used to efficiently find the shortest path between nodes, as nodes with the smallest tentative distance are processed first. 3. Huffman Coding: Example: In data compression algorithms like Huffman coding, a priority queue is used to build the optimal prefix tree (Huffman tree) by assigning higher priorities to nodes with lower frequencies. 4, Emergency Room (ER) Management: Example: In a hospital emergency room, patients are assigned priorities based on the severity of their condition. The most critical patients are attended to first, even if they arrived last. 5. Bandwidth Management: Example: In computer networks, a priority queue is used to manage the bandwidth allocation, where packets with higher priority are transmitted first. BX Other Subjects: www.pyqspot.com Q8) c) Write pseudocode for Linear Queue Implementation using array. Ans: Pseudocode for Linear Queue Implementation u g Array Ina linear queue, elements are inserted at the rear (end) of the queue and removed from the front (beginning) of the queue. The linear queue uses a fixed-size array for storage, and the operations are typically defined for enqueue (insert), dequeue (remove), and checking if the queue is full or empty. Below is the pseudocode for implementing a Linear Queue using an array: Pseudocode for Linear Queue Initialization: + Create an array to represent the queue. + Two pointers: front and rear initialized to -1 to indicate that the queue is empty. Operations: 1. Enqueue (insert): © Input: Value to be inserted into the queue co Check if the queue is full: If rear = size - 1, then the queue is full. © Insert the element at the position pointed by rear, then increment rear. © Ifthe queue is empty (i.e., front -1), set front = 0. 2. Dequeue (remove): © Check if the queue is empty: If front == -1, then the queue is empty. co Remove the element at the position pointed by front, then increment front. © Ifthe queue becomes empty after dequeue to-l. , front > rear), reset both front and rear 3. Display: © Display the elements in the queue from front to rear. 4, Check Full: © Aqueue is full if rear size - 1 5. Check Empty: oA queue is empty if front ==-1. EX Other Subjects: www.pyqspot.com Pseudocode: Initialize: front =-1 rear=-1 queue = array of size‘n’ Function ENQUEUE(value): IF rear = size - | THEN PRINT "Queue is full” ELSE IF front =-1 THEN // Queue is empty front =0 ENDIF rear= rear +1 // Move rear to the next position queuefrear] = value // Insert value at rear PRINT "Enqueued: " value Function DEQUEUEQ: IF front = -1 THEN PRINT "Queue is empty” ELSE value = queueffront] // Get the element at the front PRINT "Dequeued: " value IF front — rear THEN // Only one element in the queue front 1 // Queue becomes empty rear =-1 ELSE front = front +1 // Move front to the next position ENDIF Function DISPLAY(): IF fron THEN PRINT "Queue is empty” ELSE BX Other Subjects: www.pygspot.com FOR i= front TO rear DO PRINT queuefi] END FOR Function IS EMPTY(): RETURN front = -1 Function IS FULLQ: RETURN rear == size - 1 Explanation: 1, ENQUEUE(value): © First, check if the queue is full by comparing rear with the maximum size. If itis full, print a message and do not insert the new element. © Ifthe queue is not full, insert the element at the rear and adjust the rear pointer. © Ifthe queue was empty before inserting, set the front pointer to 0. 2. DEQUEUE(: © Check if the queue is empty by checking if front —-1, If it is empty, display a message and return. © Ifnot empty, remove the element from the front of the queue and adjust the front pointer. © Ifthe queue becomes empty after the dequeue (i.e, front > rear), reset both front and rear to -1. 3. DISPLAY(: © Ifthe queue is empty, print a message indicating so. © Otherwise, print the elements from front to rear. 4, IS_EMPTY0: © The queue is empty if front — 5. IS_FULLO: The queue is full if rea size -1 Edge Cases: + Queue Empty: After the last dequeue operation, front and rear should be reset to -1 * Queue Full: When rear = size - 1, no more elements can be inserted unless some elements are dequeued. BX Other Subjects: www.pyqspot.com

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