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

DS With C++

The document contains solutions to various questions related to data structures, including topics such as 3-dimensional arrays, polish notation, sparse matrices, balanced binary trees, and graph types. It also discusses sorting algorithms, binary search, and operations on arrays, as well as algorithms for traversing linked lists and implementing queues. Additionally, it includes examples and explanations of BFS and DFS algorithms, minimum spanning trees, and polynomial representation using linked lists.
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)
12 views27 pages

DS With C++

The document contains solutions to various questions related to data structures, including topics such as 3-dimensional arrays, polish notation, sparse matrices, balanced binary trees, and graph types. It also discusses sorting algorithms, binary search, and operations on arrays, as well as algorithms for traversing linked lists and implementing queues. Additionally, it includes examples and explanations of BFS and DFS algorithms, minimum spanning trees, and polynomial representation using linked lists.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 27
SOLUTIONS TO PART-A (a) Glvothesyntaxfordeclaringa3-dimensional array. Answer 3 ‘AprilMay-19, Set2, Q4(a) M[2] ‘Syntax for 3-dimensional Array ‘The syntax for declaring a 3-dmensional array is as follows, ~datatype array_namefal}{a2]{03); ‘Where, 's' represents the size, Example: int Emp[2)[4)[6); : {b) Write brief notes on polish notation. Answer: Aprilay-19, Set-2, Q1(b) MIS] For answer refer Unit-II, Q14, Topic: Prefix Expression. (c)_ Whatis a sparse matrix? Give an example. Answer: AprilMay-19, Set-2, Q1(c) M[2] For answer refer Unit-IIl, Q10. (d)_ What are balanced binary trees? Why itis needed to balance binary trees? | ‘Answer : AprilMay-19, Set-2, Qt(d) M2} at. For answer refer Unit-IV, Q24. (e) Define the terms: simple graph, directed graph and connected graph. Answer : AprilMay-19, Set-2, Q1(e) M3] + Simple Graph For answer refer Unit-V, Ql, Topic: Graph. Directed Graph For answer refer Unit-V, Q2, Topic: Directed Graph: Connected Graph Ina graph, ifthereexista path between every pair of vertices then the graph isknown as connected graph. Ina connected graph, itis possible to traverse from one node to another node, Example G7) / OX Figure: Connected Graph ‘The graph is connected because there isa path from ach vertex to every other vertex. Path A to B: A+B AtoC:A-+B>D+C AtoD:A->+B>D RIL/MAY-2019, SET-2 Qp DATA STRUCTURES [JNTU-KAKINAD (f) - What Is stable sorting? Give an Answer + AprilMay-19, Set-2, Q1() ug ‘A sorting method preserves the relative order of dup keys in the file then such a method can be considered as stays class, That is, a sorting algorithm is said to be stabfe in ‘the two elements that are equal remains in the same rela position after performing the sorting. Most ofthe simple sorting methods are stable, ‘any of the sophisticated algorithms are not stable. Its possi tomake most ofthe unstable sorts as stable by indexing or ugg some other method, but this increases their complexity, Algorithm | In-place.| Stable Bubble sort v ¥ Insertion sort Quick sort Selection sort Shell sort Merge sort x6 iHinelude ud Look for the SIA GROUP Loco {Yon the TITLE COVER bofore you buy struct node struct node *next; } head; void createList(intn); int main) t 1 int, choice; printf("Enter the total numbet of node: scanf("%d", &n), : createList(n); printf("\nData in the list \n displayListO; printf("nPress 1 to reverse the onder of singly linked lst"); scanf{"%d", &echoice) iffchoi printf("\aData in the list\n"); displayListO: return 0; d void createList(int n) { struct node *newNode, “tempi int data, is head = (struct node iffhead = NULL) { print{("Unable to allocate memory 3 else { printf("Enter the data of not seanf{"%d", data); hhead->data = data; : ; head->next = NULLS +)malloc(sizeofistruct node); de 1" i " newNode = (struct node ymatloet intnewNode = NULL) pent Urabe to allocate memory breaks , } . else { printf(’ seant("%d", data): newNode->data = datas inewNode->next = NULL: pmter the data of node Yd: ", D5” temp->next = newNode: temp = temp->next; J } print(('SINGLY LINKED LIST, (CREATED SUCCESSFULLY"); ) ) , void reverseList ( struct node *prevNode, “curNode; ifhead != NULL) rl prevNNode = head; curNode= head next hed = head->nent; prevNode->next = NULL; * whitehead != NULL) ee head = head>next; curNode->next = prevNode; prevNNode = curNode; curNNode= head; ) + edd ~ proyNedes 0 printf("SUCCESSFULL) Tin" Y RE i : VERSED LISTin"); «_fortie’ M FOR ENGINEERING STUDENTS ‘SPECTRUM ALL-IN-ONE JOURNAL FOR ENGI r 2 : SIA GROUP. ab void daplayEtO t struct node *temps if{head = NULL) ' ‘ tet temp = heads while(temp != NULL) t printf("Data = %d\n", temp->data); ‘temp = temp->next; ae Scere tare stacy Boreas rerun’ (©) Explain with an example, how linked lists can be used for polynomial representation. Answer : . April/May-19, Set-2, Q4(b) Mi For answer refer Unit-IIl, Q24, Topic: ‘epresentation of Polynon 'Q5.: (a) Discuss about different roprosontations oF binary trees. Give an example for each. Answer : J ApriliMay-19, Set-2, a5(a) MI For answer refer Unii-IV, QI8. Look for the SIA GROUP Loco 4 onthe TITLE COVER before you buy jaiilMy-2019 (Sét-2) Question p er (b) Insert the sequence Per With Solutions. aes bre hen ote 40 ana 70. gene 8 10,20, 30,40, 60, 60,70, 60 ase an | . (Present the operations one after the other) isi tum degree of the Aprtumay.19, Set 2, 050) MIT ~ i that Jement ic., 10a follows, ofthe B-Tre be t= 3, Given thatthe Bree i intally empty So the Fis ti Insert 10 rf Oe ‘The maximum number of keys in a node canbe calculated as 2* ¢~ 1- = 2x3-1=6-165 Insert 20, 30, 40 and 50 Insert 20, 30, 40 ‘and SO in the root node itself as the maximum. Sete es Insert 60° s a 10 ][20 40 |[50]] 60 ‘ Insert 70 and 80 4 30 10 []20 140 [[ 50 [[60]] 70 |] 80 > Insert 90 “This insert wil spit the right child and therefore the middle element is ncluded inthe parent node, The resultant B-iree will be, : 30]] 0 i Tol 20] Lolo LelzoTso ‘ Delete 40 30] 60 : 10] 20 70 |[80 [90] Delete 70 ! . 5 80 SPECTROM ALLIN-ONE a DATA STRUCTURES [JNTU-KAKINAD, 8.28 ° . Q6. (a) Differentiate between BFS and DFS with algorithms and examples.” Ian et Staite tivo ances "nora 19, Sot2, Qs uy MR “ Differences between BFS anid DFS ’ | Foranswer refer Unit-V, Q3. i Algorithm for BFS . ; 1, [Initialize all nodes to ready state) state[V] = 1 [Here V represents all nodes of graph) : [place starting node *S* in queue’and change its state'to waiting] state[S] = 2 1. 3. Repeat through step 5 until queue is not empty. a ‘i 4. [remove anode N from queue and change its status to visited): state[N] yey , 5 [edd to queue all neighbours W of ‘N' which are in ready state and change their status io waiting state]. “«. state[W]=2. fee : 6 Retum i ae Example for BFS ; “ : 3 For answer refer Unit-V, Ql6, Topic: Example [Breath First Search (BFS)]. Algorithm for DFS : i “f 1. PInitiaize al the nodes to ready state and stack to empty] ee > State[v] = 1 [+> 1 indicates Ready state] 2 [Begin with any arbitrary node ‘s’in graph, push it onto stick and change its state to waiting] ‘state[s]=2[- 2 indicates waiting state] ¥ 3. Repeat through step 5'while stack is not empty : 4. [pop node N of stack and mark the status of node to be visited] - state[N] = 3 [- 3 indicates visited) 5. [Push all nodes w adjacent to N into stack and ‘mark their status as waiting] a : statefw] =2 " 6. ‘If the graph still contains nodes which are in ready state goto step 2. : \ 7. Return, i y ‘ Example of DFs a For answer refer Unit-V, Q16, Topic: Exaviple [Depth First Search (DFS)]. "(b) Compute minimum cost spanning tree for the graph below using Prim's algorith 00k for the SIA GROUP Loco ag on the TITLE COVER before you buy AptiMay-2019 (Set-2) Questio, Step 1 Start with the first vertex ie, a. The edge weights of this vertex are compared i.e., 5 is compared with 3. Since $ > 3, the edge {a, c} is'selected. Step2 ‘Now consider the vertex 'c- The edge weights of this vertex are compared and the edge with smallest weight is selected ie. (c, 6} with weight 4s selected. Step3 The edge weights {c, d) is selecte das it has 5 7. n Paper wi 3 29: ‘Answer = ith 8 . 8. aay > lutions ‘ : : Given weighted graph G ig, Step ‘The edge weights of d and b are compared to find mini- mum cost tree to e. Therefore, the edge b toe is selected, as it has minimum edge weight ic., 2. 2(©) Step 5 “The edge weight of e-are compared and the edge {e,f} js selected as it has minimum weight. Step 6 ‘The edge weights of fare compared and the edge {f, 2} is selected, The resultant minimum cost spanning tree ‘The resulting graph obtained is a minimum spanning trée ‘which the comparisons made by the tree algorithm are totally 6, forn=7 vertices, (n- 1) ie. (7 ~1)] comparisons are done, » a7. (a) Write and expiain Binary Search algorithm. Also mention its time complexity. April/May-19, Set-2, Q7(a) M[7] Answer Binary Search Algorithm For answer refer Unit-VI; QUS, Topic: Algorithm for Binary Search, nite ‘Time Complexity For answer refet Unit-IV, Q13, Topic: Time Complexi wary Search, ms oe : PART-A Qi. (a) List different operations that can. be performed on an array. Answer AprivMay-19, Set-3, Qt(a) M[2) The different operations that ean be petformed onan array are, 1, Traversing Using this operation, all the elements present in an array ‘ean be visited. The input given for this operation is array with “n'clements and the output obtained depends upon the process( ) method. Ifthe process( ) is used for displaying an element on. the screen say A[i] then the output will be element present at » the position. 2 Sorting Sorting is an operation usifig which the elements in an array can be sorted (ot) arranged in ascending/descending order. ‘The input for this operation is an airay consisting of integer ~data. The output is sorted array of elements, For carrying out this operation, two methods are required. One is the orden( ) method that checks iff two elements are in order (ot) not. The ‘second method is the swap( ) method that interchanges the two elements if they are not in order. 3. Searching Searching is another operation’ which is used for searching a particular element in the array. The' input for this operation isthe ‘key" element that i to be searchéd. The outpitt obtained can either be the ‘key’ upon successful search (of) ‘message saying that “key element is not present in the array”, A variable ‘result’ is initialized to “0” indicating that the search is not completed. The key element is compared with every ‘element present in the array. If match is found then the result variable will be set to "I" and the location of the key element in the array will be retumed. I'no match is found then a message is displayed indicating that “key element is not present in the array’ 4. Insertion Insertion operation performed on an array inserts an element into the array. The insertion is only possible when the array is not full. For this purpose, first the array must checked whether it can accommodate new element or not. If yes then the input provided will be the key element that isto be inserted and the location of it inthe array. The output thus obtained will be an array with the added element. If the array is full then a message will be displayed saying that insertion operation cannot be perforined as the array is full 5. Deletion Deletion is an operation performed on the array in order to delete vertain element from it. This process will be carried out by pushing each element present in the array, one place up, ‘The input provided for this operation is the key clement that heeds to be removed from the array. Then this key element Will bé searched whether itis present (or) not. If yes then each element will be pushed one place up and thus the key will be deleted, If no then # message is displayed saying that the key is not found, 6. Merging Merging is considered to be the most significant operation petformed on arrays. This operation has the ability to merge (or) combine elements present in two different arrays into a single array. The input required to perform this operation is the two.” arrays containing their own elements. Then the lower and upper bounds for both these arrays are.determined. Later, an empty array is considered whose first partis filled with the elements of | first array and the last partis filled with the element of second array. Then, this aray is displayed as output, The other way of performing this operation is that the elements of the second array | ‘can be appended to the elements of first arrays and.vice versa. (b) What is a queue data structure? Answer : ApriliMay-19, Set-3, Q4(b) M[2} For answer refer Unit-II, Q3, ‘ (c) Write C structure to declare node of a double-linked list. AprilMay-19, Set-3, Q1(c) M[2]_ ‘The self-referential structure of doubly’ linked list is as follows, 3 struct node* create(int data) t : struct node *ptr = (struct node *) malloc(sizeofistruct node); ptr > data = data; “ ptr—> next NULL; return ptr; Answer : (a) Dofino the terms: root, leaf and siblings with respect to trees. AprlvMay-19, Sets, 4g) M9] nswer ¢ Root For answer refer Unit-IV, QS(i). Leat For answer refer Unit-lV, QS(ii). Siblings For answer refer Unit-lV, QU3, topic » Look for the SIA GROUP Loco QR on the TITLE COVER before you buy ‘ pottiay-2019 (Set-3) Quostion ti oes le range of applications in the used in the analysis of . is of electrical Itis used to study the struc inte ‘ure of molecules in chemical Itis used in the fields of genet and social sciences. att 4, Itis used in planning projects, 5, It is used in the representation of ai 1s used in the representation of sting routes and Present the ti Pratttotane cae Complexity of quick sort Answer # AprlvMay-9, Seta, For answer refer Unit-VI,Q33,. on ee eee : > PART-B a2, (a) With a neat sketch, explain the model of Answer ApriliM For answer refér Unit-l Q13._— (b) Explain how linear arrays are stored and statistical mechanics va 19, Set3, 2a) MT] traversed. : Amswert ‘Aprivitay-19, Set-3, 02(b) MIT] Storing Linear Arrays For answer refer Unit-1, QI6. ‘Traversing Linear Arrays For answer refer Unit-I, Q17, Topic: Traversing. _ GS. (a) Explain how postfix expressions arp evalu- ated using stacks. Give an example. Answer + ‘AprivMay-49, Set, 32) MIT] For answer refer_ Unit-II, Q20. queues and b) Differentiate between regula © irar queues with insert and delete OP 2 erations. Answer + ‘Apeay-19, Set, 0300) M7 Reg Queue . é EC items inwhich rlew “Aqueue isan ordered Coleone ig ems items may be inserted at one may be deleted from other also known as FIFO (First-In-t ue ‘lement which is inserted first will Pe deleted, : E 5 a to insert Enqueue and Dequeue OFF re used to ins and delete the iteins respectiv© oo i spay o ue front and re8" Poe sco ine pear bean ‘letion Hae rere: FRONT and REAR POETS N-OME JOURNAL (®) Enqueue (Insert) Operation ‘Before inserting the element check full ornot to guarantee that there is ne eys1!0 be represented by QUEUE [12] durin rt : will move away fom the FRONT ane (B=, 5070071 Tnerementing the REAR variable ven 19M op REAR eM obere Nis the size of vecueue: The 207 | ‘enqueue operation is shown below, Insert (Queue, N, Element, Rear) 1. IF (Rear =N) then ee write "Queue is full” 2. Else fiewral # 3, Front= front + 1 at . 4. Rear rear+1 5.” Queue [rear] = Item 6. Endif : 5. Bnd. 2 Example 5 ! ‘Conaider a queue of size four insert the lemme 15, 20, into it. The insertion begins 2% follOws > Initially the queue looks like this, Front = 0, ot Rear => Insert queue, 4, 5, 0) and insert. the 5 Tet wie Froot=1 Rear=1 => Calliinsert (queue, 4, 10, 1) and inseit the element 10 => Call insert (queue, 4, 15,2) and inser! Front s] wo | is Frost=1 Rear ‘ => Call insert (queBe; 4, 20,3) and iit he elena 20 ro | a5 J Front = 1 Rear= 4 Call insert (que, 4, 25,-) and insert he eleent 256 Since Rear = 4, queue is full that resulls into queue overow Hence insertion fil. SIA GROUP as + eet 3.36 (b) Dequeue (Delete) Operation When deleting the element, the front pointer moves towards the rear pointer. Deletion is done by incrementing the front. This makes the front variable point to the next element, ‘The algorithm for dequeue operation is shown below. Delete (queue, front, rear, element) Cire 2 Circular queue isa variant ofa queuie in which elements , are stored in circular manner, These queues are implemented), using arrays. The main purpose of using citcular queue is to overcome the problem of unutlized space present in linea, queue, Similar to linear queues circular queues also insert the item from rear end and delete the item from the front end. Unlike in linear queue (where no more elements can be added once ” 1, If (front = = rear) then the end of the array is marked) in circular queue elements can 1 . neacoe be added eventhough end of array have been reached. write “queue is empty”. : a Let us cbnsider an array cqueue, that contaitis ‘k* 4 2 Else elements in which equeué{1] comes after equeue{{] in the array, a ‘A linear queue can be transformed to circular queue when last “| 5.°—" Ekcneat = qoeae [fat . oom comes just before the first room. 3 4... Front= front +1 5. Endif 6. End. Example on ‘Consider the deletion of the elements from the following : a Fag | 13-0 Figure: Circular Queue 7 The two primitive operations performed on circular__| 5 Rear=4 queues are, “i 4 E inser ti : = Call delete (qucie, 1,4, 5) and delete the element 5 haem be hieed ° ; (b) Dequeue(deletion) operation. . fo [ 150] 99 (@) . Enquene(Insertion) Operations 5 ; y Algorithm Enqueue 4 Fram 2 Rear =4 Input . nm . "4 4 = Call delete (queue, 2, 4, 10) and delete the element 10 An ITEM(element) which should be inserted on the - i circular queue. ‘ oe | [1s fw Data Structire — a An array A for representing circular queue with two Front=3 Rear=4 Pointer namely FRONT and REAR: Ni = Output ‘ Call delete (queue, 3, 4, 15) and delete the element 15 20 Rear =4 Front =4 => Call delete (q jucue,'4, 4,20) and delete the element 20 Front 5 Rear =5 =>. Call delete (queue, 4, 4 element). And, error is reported since (front =rear= 4) that results into queue underflow. Since the queue is empty deletion fails. The given input called ITEM(clement) inserted on. circular queue. Step1: Check whether queue‘ full or empty I{FRONT = 0) Step2: Initialize FRONT with 15 Front = 1 Step3: Initialize REAR with 1 REAR=1 Step4: A[FRONT] = ITEM 1 Step3:Go to else ‘Step6:Next = (REAR mod LENGTH) + 1 a If{next # FRONT) then

You might also like