0% found this document useful (0 votes)
612 views75 pages

DSA Easy Solutions

Uploaded by

omchaudhari7559
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)
612 views75 pages

DSA Easy Solutions

Uploaded by

omchaudhari7559
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/ 75
es Js CaS¥-solutions +n As per the New Revised Syllabus (2019 course) Y-) of Savitribai Phule Pune University wef. academic year 2020-2021 LA/ = DATA STRUCTURES AND ALGORITHMS (Code : 210252) “QUICK READ SERIES” Semester IV Computer Engineering / Artificial Intelligence & Data Science echKnowledge ublications easy - - solutions | Savitribai Phule Pune Eon As per New Credit System Syllabus(Rev. 2019) of Savitribai Phule Pune University with effective from Academic Year 2020-2021 Data Structures and Algorithms (Code : 210252) “Quick Read Series” Semester IV - Computer Engineering / Artificial Intelligence & Data Science EPE122A Price ¢ 120/- OY Nehhnenttys ii Syllabus In-Sem. Exam — 07 hrs Hash Table : Concepts-hash table, hash function, basic operations, bucket, collision, probe, synonym, overflow, open hashing, closed hashing, perfect hash function, load density, full table, load factor, rehashing, issues in hashing, hash functions- properties of good hash function, division, multiplication, extraction, mid- ‘square, folding and universal, Collision resolution strategies - open addressing and chaining, Hash table overllow- open addressing and chaining, extendible hashing, closed addressing and separate chaining. Unit IT: Trees ee ‘Tree : basic terminology, General tree and its representation, representation using sequential and linked Organization, Binary tree- properties, converting tree to binary tree, binary tree traversals(recursive and non- recursive): inorder, preorder, post order, depth first and breadth first, Operations on binary tree. Huffman Tree (Concept and Use), Binary Search Tree (BST), BST operations, Threaded binary search tree- concepts, threading, insertion and deletion of nodes in n-order threaded binary search tree, in order traversal of in-order threaded binary search tree. End-Sem. Exam —— 07 hrs Basic Concepts, Storage representation, Adjacency matrix, adjacency lst, adjacency multi list, inverse adjacency 'st Traversals : depth fist and breadth fst, Minimum spanning Tree, Greedy algorithms for computing minimum Spanning iree- Prims and Kruskal Algothms, Dikials Single source shortest path, All pars shortest paths- Floyd- Warshall Algorithm Topological ordering, Unit IV : Search Trees 08 hrs Symbol Table : Representation of Symbol Tables- Static tree table and Dynamic tree table, Weight balanced {ree - Optimal Binary Search Tree (OBST), OBST as an example of Dynamic Programming, Height Balanced Tree: AVL tree, Red-Black Tree, AA tree, K-dimensional tree, Splay Tree, Unit V : Indexing and Multiway Trees Indexing and Muttiway Trees : Indexing, indexing techniques-primary, Secondary, dense, sparse, Multivay Search tees, B-Tree- insertion, deletion, B+Tree- insertion, deletion, Use of B+ tree in indexing, Trie Tree. Files : Concept, need, primitive operations. Se Direct Access File- Concepts and Primitive operations, Inde indices, structure of index sequential file, Lin Unit VI : File Organization cellular partitions. Unit Il Unit IV Unit V Unit VI ,quential file x ked Organization Table of Contents Search Trees Graphs Indexing & Multiway Trees File Organization organization- concept and primitive operation, ced sequential file organization-concept, types o ‘muti list files, coral rings, inverted files ang 97 hrs aaa 1to18 | 19 to 33 34 to 57 58 to 71 Savitribai Phule Pune University Semester IV (Computer Engineering) Data Structures and Algorithms Unit III : Graphs Q.1 Define a graph. SPPULMay15,2 Marks Ans. Definition of Graph A graph Gis a set of vertices (V) and set of edges (E). The set Vis a finite, nonempty set of vertices. The set E is aset of pair of vertices representing edges. G = (VE) V(G) = Vertices of graph G E(G) = Edges of graph G ‘An example of graph is shown in Fig. 3.1. © Fig. 3.1: Graphs ‘The set representation for each of these graphs is, siven by V(G,) = (A,B,C, DEF} V(G,) = {A,B,C D, EF} (Gs) = {A,B,C} E(G,) = {(A,B),(A, C),(B, C),(B, D),(D, E),(D, F),(E, F)} E(G,) = {(A,B),(4, C),(B, D),(C, E),(C, F)} E(G,) = {(A, B),(A,C),(C, B)} @.2 Define Undirected and Directed Graph. (4 Marks) Ans.: Undirected Graph ‘A graph containing unordered pair of vertices is called an undirected graph. In an undirected graph, pair of vertices (A, B) and (B, A) represent the same edge. boas c— > @ Fig.3.2(@): Example of an undirected graph The set of vertices V = {1, 2, 3, 4, 5}. The set of edges E = ((1, 2) (1, 3), (1,5), (2.3), 4), 8,4, asp Directed Graph ® A graph containing ordered pair of vertices is called a directed graph. Ifan edge is represented using a pair of vertices (V,, V,) then the edge is said to be directed from Vy toV>. ‘The first element of the pair, V, is called the start vertex and the second element of the pair, V; is called the end vertex. In a directed graph, the pairs (V,, V;) and (Vz Vs) represent two different edges of a graph. Example ofa directed graph is shown in Fig, 3.2(b). Fig. 3.2(b) : Example of a directed graph ‘The set of vertices V = (1, 2,3, 4,5, 5}. ‘The set of edges = {(1,3), (1,5), (2,1), (2,4), G4), (4.5). Quick Read Data Structures and Algorithms (SPPU) tions of graphs in the area of @.3 With example define the path and cycle wart graphs. Ans: Path A path from vertex Va to Vy is a sequence of vertices Voy Vis Vz w= Vat» Vor Here, Vo is adjacent to Vi, Vi Is adjacent to V; and V,.. is adjacent to V,. The length of a path is the number of edges on the path. A path with n vertices has a length of n~ 1. A path is simple if all vertices on the path, except possibly the first and last, are distinct. cycle A cycle is a simple path that begins and ends at the same vertex. Fig. 3.3 is an example of a graph with cycle. + ABDAisacycleoflength3 + BDCBisacycle oflength 3 * ABCD Aisacycle oflength 4 A B D c Fig. 3.3: A graph with cycles 2.4 With example define the degree of node wir. graphs. OR With example define the isolated node wrt graphs, SE EERNA Ans: Degree of node The total number of edges linked to a vertex ig called its degree. The Indegree of a vertex Is the total humber of edges coming to that node. The outdegree of a nodes the total number of edges going out from that node. A vertex, which has only outgoing edges and no incoming edges, is called a source, A vertex having only incom outgoing edges is called a sink, vertex is one and outdegree is zero called a pendant vertex. When the d Itis an isolated vertex. ng edges and no When indegree of a then such a vertex ig learee ofa vertex is 0, three appli ‘Explain any t! oF comuter Enginoetn Ane Graphs ‘Applications of ‘ ai applications of graph split broadly into three vataguien: : ) First, analysis to determine structural ag properties of a network, such as the distribution of vertex degrees and the diameter of the graph. A vast number of graph measures exist. b) Second, analysis to find a measurable quantity within the network, for example, for a transportation network, the level of vehicular flow within any portion of it. ©) Third, analysis of dynamic: properties of network. Map of a country can be represented using a graph, Road network, Air’network or rail network can be represented using a graph, Connection among routers in a communication network can be represented using a graph. Routing of a packet between two ‘communicating nodes can be done through the shortest path, Graph theory is useful in biology and conservation forts where a vertex can represent regions where Spent GEC aid the edges represent Ton Paths, or movement between the regions. THs information is important when looking at breedi Cae Defi ne MMA SPaNnIng tree with example, (3 Marks) ns. Minimal Spanning Tree The cost of a graph is the edges in the wet ighted gra = (V.B) is called mine ee ‘minimal sp Sum of the costs of the Spanning tree of a graph ™ cost spanning tree or simply Gifits cost is minimum. led mininn "Anning tree of @s Enns ¥ Data Structures and Algorithms (SPPU) Quick Read yo of \o te % Fig. 3.4 G— A sample weighted graph. Ty Aspanning tree of G with cost 5 +9 = 14 ‘Ty A spanning tree of G with cost 10 + 9 = 19 ‘Ts Aspanning tree of G with cost 5 + 10 = 15 Therefore, T, with cost 14 is the minimal cost spanning tree of the graph G. A typical application for minimum-cost spanning tees can be seen in the design of communication networks. The vertices of a graph represent cities and the edges possible communication links between the cities. A minimum-cost spanning tree represents a communication network that connects all the cities at minimal cost Q.7 Explain with suitable example the various storage, structures for the graph. Ans.: Representation of Graphs ‘Methods for representation of graph, includes : 3. Mullet Fepresentation of Graph Fig. 3.5 : Representation of graphs 1. Adjacency Matrix ‘A two dimensional matrix can be used to store a graph. A graph G = (V, E) where V = {0, 1, 2, n= 1) can be represented using a two dimensional integer array of sizenxn. {int adj{20][20}; can be used to store a graph with 20 vertices. adjil{j] = 1, indicates presence of edge between two vertices i and j = 0, indicates absence of edge between two vertices i and j ‘A graph is represented using a squaré matrix. Adjacency matrix of an undirected graph is always a symmetric matrix, Le.an edge (,j) implies the edge (i). Adjacency matrix of a directed graph is never symmetric adifi][j] = 1, indicates a directed edge from vertex ito vertex j. cont Fig. 3.5(a) : Graphs G,, G,, G, and G, 2. Adjacency List {A graph can be represented using a linked list. For each vertex, a list of adjacent vertices is maintained using a linked list. It creates a separate linked list for each vertex V, in the graph G = (V, E) Fig, 3.5(6) :A graph List of adjacent vertices to vertex 0 “oS 0S“ List of adjacent vertices to vertex 1 List of adjacent vertices to vertex 2 Hood 2 —EE-GE-E] 7es CEILS Data Structures and Algorithms (SPPU). List of adjacent vertices to vertex 3 * GRO -EHa], List ofadjacent vertices to vertex 4 ot OEE Fig. 3.5(€) Adjacency list for each vertex of graph Adjacency list of a graph with n nodes can be represented by an array of pointers. Each pointer points to a linked list of the corresponding vertex. Fig. 3.5(d) shows the adjacency list representation of graph of Fig. 35(b). ° 1 Head {en ray of pointers) Fig. 3.5(¢) : Adjacency list representation of the graph 3. Multilist Representation of Graph In adjacency list representation of a graph, each edge (1 ))is included twice : 1. Once in the list of vertex" 2. Once in the lst of vertex. This drawback may be removed if the adjacency lists are maintained as multiliss. In a multilist, a node can be shared by several lists. Each edge must be connected to two lists and the structure of an edge (Jj) looks like the following, Next edge in adjacency Next edge in adjacency list for vertex "i" list for vertex 4" The adjacency multi-list representatio ‘sample graph shown in Fig. 3.5(e), of the Quick Read Fig. 3.5(e):A sample graph for multilist 4, Inverse Adjacency Lis Inverse adjacency list can be used to determine the indegree of a vertex. The inverse adjacency list keeps track of edges coming into a vertex. The inverse adjacency list of the graph shown in Fig. 3.5(f) is shown in Fig. 35(8). & Fig. 3.5(f) : A sample graph for inverse adjacency list 14(5,6) 258.6) 35 (4) 45 (2) Ca ok ljacency list for graph 2 For the folowing graph obtain (Then degree and out degree of each vertex (i) Ws adjacency matrix (i Us Adjacency ist representation, (6 Marks) @=22 15 W_ data structures and Algorithms (SPPU) ‘Ans. : 2) Indegree and outdegree of each vertex Vertex No. | Indegree | Outdegree 1 3 0 2 1 1 3 1 2 4 2 1 5 1 H 6 1 fl 7 1 i 3 2 r @ 2) Adjacency matrix 123 456768 1] 0[o[o[olofofofo 2{s[o[o fo [olololo a{10[a[o[o folololo s[ofoli[ofolololo s{o[o[o|as[olsfolo 6{ 0 [ol o[sofolol ols 70 [o[ 0 | o [ololo| 0 a{a7fofo[olofofolo (b) 3) _Adjacency ist Ver t “Weight 2 ° fsis——enEr 5 GES—n : GiS— oP} GE > oa ‘CoE © Fig. 36 as List and explain the techniques of traversal of graphs, (6 Marks) Quick Read An ‘Traversal of Graphs Most of graph problems involve traversal of a graph. ‘Traversal of a graph means visited each node and visiting exactly once, Two commonly used techniques 2.Breadth First Search (BFS)| Fig. 3.7 : Traversal of graph 1. Depth First Search (DFS) It is like preorder traversal of tree. Traversal can start from any vertex, say V,- Vis visited and then all vertices adjacent to V, are traversed recursively using DFS. DFS (G, 1) is given by Fig. 3.7(2) : Graph G @ Visit) @) DFS (,2) DFS(6,3) } allnodes DFS (6,4) [ adjacentto1 DFS (6,5) Since, a graph can have cycles. Avoid re-visiting a node. To do this, when we visit a vertex V, we mark it visited. A node that has already been marked as visited, should not be selected for traversal. Marking of visited vertices can be done with the help of a global array visited|}. Array visited] is initialized to false (0). Algorithm for DFS n& number of nodes 1) Initialize visited] to false (0) for (i=0;1<:n; 144) visited 2) vold DFS (vertex) (DFS starting from i] Visited @ Gnu WF _ ata structures and Algorithms (SPPU) for each w adjacent tot f(t visited) DFS(W); 2 | Fig. 3.7(b) : DFS traversal on graph of Fig. 3.7 DFS traversal on graph of Fig. 3.7. Node i can be used for recursive traversal using DESO. Cors@) 1 > Node iis already visited Breadth First Search (BFS) It is another popular approach used for visiting the vertices of a graph. This method starts from a given vertex Vo. Vo is marked as visited. All vertices adjacent to Vo are visited next. Let the’vertices adjacent to Vo are Vso, Vs, Viz «Vane Vi» Via ~ Von are marked as visited. All unvisited vertices adjacent to Vay. Viz o=Vig are visited next, ‘The method continues until all vertices are visited, ‘The algorithm for BFS has to maintain a list of vertices which have been visited but not explored for adjacent vertices. The vertices which have been visited but not explored for adjacent vertices can be stored. in queue. fa lly the'queue contains the starting vertex, In every iteration, a vertex is removed from the queue and its adjacent vertices which are not visite as yet are added to the queue, ‘The algorithm terminates when the queue becomes empty. Fig. 3.7(6) gives the BFS sequence on various graphs. Quick Read Fig. 3.710) : BES traversal on G,, Gz, G, and G, BFS sequence: 6,9 Vo | Vi Vo Vs Va Vs Ve I Vo G9 Vo | Vi Vo | Vs Va Vs Vel V2 G3 Vol Vi Vo | Vs Ve Va IVs Ve, G9 Vo 1 Vi Va Vs 1V2 Ve Algorithm for BFS /* Array visited[] is initialize to 0*/ /* BRS traversal on the graph G is carried out beginning atvertexV*/ void BFS(int V) { 4: queue type variable; . initialize g; visited(V]=1; /* mark V as visited */ add the vertex V to queue q; while(q is not empty) { Ve delete.an element from the queue; forall vertices w adjacent from V { if(visited{wy) { visited[w] add the vertex w to queue q W_data structures and Algorithms (SPPU) @.10 Draw the BFS traversal of the following graph represented using adjacency lis EME °+—-01 3-1. 17—(o 3-41} -2T 2+-013-GLH, s}—-GI -EL Eo, ++-GI3—-G1L}-4Ooy Fig. 3.8 +3} ¥ Ans.: The graph is given by : Q Qo BFS traversal Step 1: Step 2: 0) Q © ® © :. BRS sequence =0, 1,4,2,3 0-1,4-2,3 Q.41 Define Greedy method. Ans. (2 Marks) The greedy method is a very simple technique and it can be applied to a wide variety of problems, Greedy algorithms work in phases in each phase, a decision is made that appears to be good, without regard for future consequences, + Ateach stage, select an input. * Input selected is added to the set of optimal solution. Quick Read Selection is made on the basis of some selection procedure, + Inclusion of next input into the partially constructed ‘optimal solution should result in a feasible solution. Ans. Knapsack Problem Given n objects and a knapsack(bag). © Each objéctis of fixed weight. © Knapsack has capacity m (total weight of objects used for filing it) © There are different types of objects. © Each type of object gives us a certain profit. Objective Fill the knapsack with suitable objects to maximize the profit, Constraint Total weight of objects < m Formally, the problem can be stated as : * Object has a weight w, andit gives a profit of P, + A fraction x(12 x;20) of object i is used to fill the knapsack. Thus, Objective is to maximize T Pix ied With the constraint YS was-¢m, Greedy approach 41, Select the object that gives, maximum profit per unit weight. le, Select the object with largest value of P,/w, Use the object for filing up of knapsack, Now one of the two things can happen, Knapsack is led to its complete capacity, Object {is exhausted and some ‘more objects can be added to knapsack, " @s' solutions Quick Read WH _ata Structures and Algorithms (SPPU) Example Consider the following example of knapsack. ‘There are three types of objects, n=3 Capacity of knapsack m = 20 Profit due to objects = (25, 24, 15) (Profit due to object 1=25 Profit due to Object 2=24 Profit due to Object 3=15) Weights of object (18, 15, 10) Calculating profit per unit weight: 25 18 24 15 45 10 24 15 25 Hereqs *i0 > 18 Step 1: Select the object 2 for filling the knapsack. X= 1{All objects of type 2 will be used for filling the knapsack) Capacity remaining after filling of object of type 2 = 20-1525. Step2: Select 1/2 of objects of type 3 to-fil the knapsack. . X= 1/2 Step 3: Since, the knapsack is fled to its complete capacity: <0 c.Total profit = 0x 2541x244 1/215 24475 =315 Connected Components Traversal algorithm DFS or BFS can be used for finding out the connected components of a graph, All the connected components of a graph can be obtained by making repeated calls to DFSQ or BFSQ) with V a vertex not yet visited. “C’ Function for Printing Connected Components of a Graph define MAX[20] int G[MAX][MAX]; int visited [MAX] int; int component) { int count; count=0; for(i=Oiensi++) visited| for(i= if{visited{i}; ( BES(H); count++; } return(count); Q.13 List and explain popular techniques for constructing a ‘minimum cost spanning tree. (8 Marks) Ans.: Minimum Cost Spanning Tree With applications of weighted graphs, it is often necessary to find a spanning tree for which the total Weight of the edges in the tree is as small as possible Such a spanning tree is called a minimal spanning tree oF minimum cost spanning tree, Fig. 39 shows a wei "6 39 shows a weighted graph and its minimum- cost spanning tree, ZFeasy-sotutions W_ata Structures and Algorithms (SPPU) Techniques of Minimum Cost Spanning Tree 1. Prim’ algorithm 2. Kruskal algorithm] Fig. 3.9(a) : Techniques of minimum cost spanning tree Prim’s Algorithm Let the graph G = (V, E) has n vertices. Step 1: Choose a vertex V, of G. Let Vp = (V;} and | Step2: Choose a nearest’neighbour V, of V_ that is adjacent to V, V, € Vz and for which the edge (Vp ¥) does not form a cycle with members of Er. Add V, to Vz and add (V, V) to Ey. Step 3: Repeat step 2 until | Ey | = n ~ 1. Then Vp contains all n vertices of aid E; contains the edges of the minimum cost spanning tree ofc, Im the above algorithm, begin at any vertex of G and construct a minimum cost spanning tree by adding an edge to a nearest neighbour of the set of vertices already linked. The edge to be added should notform a cycle, Algorithm avoids cycle in the minimum cost spanning through a rather better approach, * Algorithm works in stages. In each stage, one new vertexis added through an edge to the tree, ‘+ At each stage, a set of vertices that have already been added to the tree and the remaining that have not been. Ifa vertex is in the tree then I /(vertex iis notin the tree. ‘Find a new vertex V to be added to the tree, such that © (u, V) isan edge in the graph © uisin the treeand Vis not Quick Read © (u, V) is the smallest weight edge among the remaining edge. © Two arrays Distance{] and from{] are used to find the new vertex V to be added to the tree. ‘* Initial values of visited{}, Distance[] and from{] are shown in the Fig, 3.9(b). o}3|1}6[2fe| distance Oli) 48 ofolofololo from = Wate aes tothe wee Fig. 3.9(b) : Graph and the initial values of visited{], distancel], from[] and the tree ‘Start constructing the spanning tree beginning with the vertex 0. Array Distance[] shows the distance of every vertex from the vertex 0. Array from{] says that the distances in the distance[] array are from the vertex 0. 2. Kruskal’s Algorithm {eis another method for finding the minimum cost spanning tree ofthe given graph, In Kruskat’s algorithm, cilges are added to the spanning tree in increasing order of cost I the edge E forms a cycle in the spanning, it i Alscarded. Fig. 3.9(¢) shows the sequence in which the edges are added to the spanning tree, sonny Quick Read F_ata srvetures and algorithms (S°PU) 10 memvanning tree TeTges Two Fig. 3.9(¢) :A graph G and its ‘minimum cost spanning tree Formally, Kruskal’s algorithm maintains a collection ‘f components. Initially, there are n components. Every node isa component. Component number 0 = ((V;), 6) -[A component with one vertex Vo and no edges} Components number 1 = ((V;), 6) Components number 2 = ((V,), 6) Components number 3 = ((V;), 6) Components number 4 = ((V,), 6) Components number 5 = ((Vs), 6) A vertex V; belongs to component number kif belongs{Vj) is equal to k. Initial configuration of belongs(] is O42 3 4 5 6+ vetoes SE ETe cCompenern, Fig. 3.9(d) :A graph G and initial list of components ‘Adding an ede to one. ; sil (Vo Vz) with weight 1 is added to the en \e of the vertices as spongy ofthe verter 3 Yl be merged into a single component. To carry out the above operation, two functions are written: Find (V) ~>gives the component number of the vertex V Union (C, C,) -> merges two components C, and C, into Cy. @.14. Represent the following graph using adjacency list ‘and fixed the minimum spanning tree using prim's algorithm. Write all the sequence of steps used in algorithm, (8 Marks) Ans. : Adjacency representation ‘aE, ae) (—-anoeno, -eEn, ell v Quick Read Data Structures and Algorithms (SPPU) in Step 2 we @eo@e ret @ © ed w\ |§ Does - DAA DAA A rom © Step 7: : ws OOOO OOO O Node at minimum distance hats ee Ra step 3: ; dee - DG A DEE wn O@eOrrergg |™ ; Gere os ee ew we NL Dene - DB A DAA A O-@ ten 7 Node at minimium distance Step 4: wwes O@©c OOF o Q © @ | 245 Consider the folowing graph represented using weer eres eT ‘jacency list. Find the minimum spanning tree for Oume - 0 BA DEE A Oo the graph by using Prim’s algorithm. fon ‘ ¢ Node at minimum distance R S3T}—{eTsT}— + — 2 crs[}~e ¢ AT3[}—> ws ©©2 OOO go g Sm En earce Hosa e Wht ee boa Fig. 3.11 Dene - 7O= = ot ee ea Soln. : The graph is shown as follows : 1 : Prim's algorithm cannot be used for a directed Node at minimum distance graph. Step 6: Hey we Qe OOOO « 60 Ooms 0 5 6 1 6 5 3 8 © Die - 0 GA DEE F fom Node at minimum distance G16 Program for constructing @ minimum cost spanning {tee ofa graph using Kruska's algorithm. (S Marks) Ans. Hincludesiostream.h> Hinclude itdefine MAX 30, ryeasy-solutions HF _Data Structures and Algorithms (SPPU) struct edge Cintwyy i class edgelist {edge data [MAX]; int; public: friend class graph; edgelistO{n=0;) void sort(); void print(); k void edgelist:sort() {inti edge temp; for(i=t;ienji++) for( nies) if(dataljjw>datafjie1}.w) {temp=datafls datalj}=datafje1}; dataljet)-temp; Lint int cost= for(i=O;ien;i++) {cout<<"\n"<>ny coutce"\nEnter the adjacency matrix: "; for‘ for(=0:jemj++) cin>>G[i) [i]; mitt) § void graph: printgraphQ) int forti-0siensies) ‘ntfind(int belongs (int vertexno); /{component no of vertexno veld untond (int belongsf, int e1, int e2, int ny; // combining two components void maint) (edges spony Braph gi; Mit, total cost; BL.readgraphg; 8LKruskal(spantise); Spanlist printg, wetchg; Quick Read WF _Data Structures and Algorithms (SPPU) 3 —$——_$—$—$———— void graphiikruskal(edgelist &spantist } {Cint belongs[MAX}.ijcn01,cn02; edgelistelist; fort forj=0;j cost [i] [lk] + cost [k) fj); cost [i] []= cost fi [k] #cést[k] [i } //display the matrix cost [N} [N] ) ‘The algorithm is explained step-wise for the graph givenin Fig. 3.17, Fig. 3.17 : Given graph @s GSEs Quick Read W_ data structures and Algorithms ($PPU) 18 Step step 4 7 trix A’, Create a 4x 4 matrix A° as the cost matrix. Greate the mal or ce 14-3 of oo of 0398 “ 4 weal toed edi 20 9 2 16 |, 3-4 0° 8 3 ch a) 6 32 On) aoe Step 5: ‘ Create the matrix A’, k: Create the matrix A‘containing the shortest path oad Zag kee a 0123 0365 = of 037 5 AS ia os 6 2 ¥ 0c ae 1] 2064 3| =.= 2 6 al 3-4 0 8 Step 3: aes, 31.2 oO Create the matrix A?, Omen 2 of 0 3°95 A211] 2094 Zi |eeae i 0S dimes Zz 0 aqaa ¥ Data Structures and Algorithms (SPPU) 49 Quick Read —>————— ll Unit IV : Search Trees aa Ans Define Symbol Tables. ‘Symbol Tables Definition : It is a standard data structure used in language processing. Information about various source language constructs can be stored in a symbol table. For example, a compiler scans the| source file and stores an identifier, a string of| characters in a symbols - table entry. Here, an identifier is a symbol. Thus a table of symbols is called a symbol table. (2 Marks) Each symbol can have a list of associated attributes. ‘A symbol along with the list of associated attributes forms an entry of a symbol table. Symbol Total Attributes 3. Fig. 4.2(a) : A Huffman’ tree for code with prefix property Ce Gr Cena) Fig. 4.2(b) : Optimal search tree when the frequency of syinbol's have been specified Fig. 4.1: A symbol table entries fora c- statement, total = +i Attributes of a symbol (Identifier) could be : Type of identifier + Its usage (eg. function name, variable, able) + Itsmemory address Symbol tables are concerned primarily with saving and retrieving of symbols. The following operations are performed on the symbol table. Insert (s,t) : Inserts a new entry for string s and associated attributes t. Lookup (s) : Returns index of the entry for strings. 2 Enlist the names of static tree tables with suilable example. SEE Ans.: Static Trée Tables Ina static table, symbols are known in advance and no insertions are deletions are allowed. Huffman tree and OBST are examples of static tree tables. Cost of searching a symbol occurring with higher frequency should be small @.3° Explain the dynamic tree tables with suitable example. SPPU=Det Dynamic Tree Tables 18,3 Marks Ans. In a dynamic table, symbols are inserted as and when they come. They are deleted when they are no longer required. AVL tree is an example of dynamic tree table, Fig. 4.3: An AVL tree Explain Dynamic programming with principle of optimality, Dynamic Programming Ans. Dynamic programming is based on non-recursive approach. In this approach, answers to the subproblems are recorded. The concept of dynamic programming with the help of fibonacci numbers. The natural recursive Program to compute fibonacci numbers is very Ge Data Structures and Algorithms (SPPU) zo ‘inefficient. To compute fibonacci Fy, there is one call to Fy. and Fy.» However, since Fy. recursively makes @ call to Fy.2 and Fy, there are actually two separate calls: to Fy.z-If trace our algorithm then see that Fy. 2is computed two times Fy-sis computed three times Fy-4is computed four times and so on, Avoid computation of same number again and again by recorded the value. ie. if Fy. is computed once, it is recorded and subsequently, recursive calls are not made. For Example Fre FytPo=1+0=1 F,, is recorded and it can be used for computation of Fs Fy= FytR=1¢1=2 @5 _Listbinary search trees with three words. Quick Read farisons number of compar + pix 3+ P2XZ+Dy Expected rs 2X24 px34d (o) ‘comparisons scted number of Brot 2+ q:X2+ PiX2+ P2X1+Ps =GoX2+ 4X24 2% 2+ 0.240.140.1408 +0.2+0.2=18 (ws.W2,Ws) = (00, if, stop) ‘Words occur with the following probabilties. (Py PePs) = (0.4, 0.2, 0.1) Probabilies of falures are given below. (04:25) = (01, 0.1, 0.05, 0.05) Find the expected access time in each case. (5 Marks) Ans. : In a binary search tree, the number of comparisons needed to search an element with success at depth d is d + 1. Similarly, the number of comparisons needed to search an element with failure (failure node at depth p)=d" " <. Expected number of comparisons (both success and failures) © Expected number of comparisons =q)x14q) x2 + R #4:%34q)%34p,x1+ ppx2+ py 1402 +0415 +015+04+044+03=17 1:48) + P62) + + Paldy#1) + gon + aid + + ad depth ofa failure node whose probability of occurrence is qy, aw ag 005 @ Expected numb Sands meee of comparisons x1 x3+ S¥ayx1 +PiX2+p.x3 + ps W_batastrcures and Algorithms (SPU) = GoX14q:X3+q.x34q,x2+P,X1+p2x3+ PIX 2 = 0.1403 +015 +0.1+04+0.6+02=1.85 Fig. 4.4: Possible binary search trees with failure nodes Binary search tree of Fig, 4.4(c) is optimal with expected number of comparisons Q.6 Define AVL tree. ‘Ans.: AVL Trees (Marks) ‘An AVL (Adelson-Velskii and Landis) tree is a height balance tree. These trees are binary search trees in which the heights of two siblings are not permitted to A 9 0 0 x a Fig. 4.11(a) : Situation known as LL (left of left) New node A is inserted in the left subtree of the left subtree of X. Balance nature of the tree can be restored through single right rotation of the node X. lon ( It is she i the Fig. 4.11(a). oe ick Read 23 <= LR : Let X be the node with BF equal to +2, of the new node A. Balance factor of the node Y, the left child of the node X becomes ~1 after insertion of A. Fig, 4.11(b) : Situation known as LR (right of left) New node A is inserted in the right subtree of the left subtree of X. Balance nature of the tree can be restored through double rotation a) node Y is rotated left b) node X is rotated right. Itis shown in the Fig, 4.11(b). @.9 Draw diagram to show different stages during the building of AVL tree for the following sequence of keys : A, Z, B, Y, C, X, D, U, E. In each case show ‘the balanced factor of all the nodes and name the type of rotation used for balancing. (6 Marks) after insertion ee @ easy-solutions as Data Structures and Algorithms (SPPU) @! 2.10 Write a pseudo C/C++ code for LR & FL rotations in AVL Trees. ‘Ans.: ‘C++’ Function for LR node *LR(node *T) { Toleft=rotateleft(T->left); ‘Terotateright(T); return(T); } “C++” Function for RL. node *RL(node *T) { ‘Tooright=rotateright(T->right); ‘Tsrotateleft(T); Feturn(T); + Quick Read for the following data by ree Oe 7m one at a ‘of the following data , 14, 22, 35, 40. 25 STORET Tree after rotating 25 Quick Read WData Structures and Algorithms (SPPU) 25 Insert 11: se.} Data | Treeafter insertion No.| tobe Inserted a} 2 Insert 97: a] as 10) 40 Insert 74 : Q.42 Create all AVL tree for the following data : 78, 21, 14, 11, 97, 85, 74, 63, 42, 45, 87, 16, 20, 19, 52. (6 Marks) Ans.: Insert 78 or Insert 21: Insert 14: @ Quick Read Insert 57: eR Gis Cotnll the AVE tiee for the folowing cats by inserting each data item one at a time, : 15, 20, 24, 10, 13, 7, 90, 36, 25 EUBIrEeaGienS Ans. : Insert 15 : Insert 20: Insert 16: @ ss Insert 19: v Data Structures and Algorithms (SPPU) 27 Quick Read Insert 7: Insert 36: 0.14 Write non-recursive functions for insertion and oletion for AVL tree. (6 Marks) Ans. : //*Non-recursive insertion and deletion into an AVL.*/ #include #include #includeciostreamh> structnode {int data; node *leftright; inthe; node *father; % } { } { int height(node * ks int thr else rh=14T->right>ht; ifgh>rh) return(ih); return(th); node * rotateright(node *x) node yexoleft; xe>left=y->right; y->right=x; x->htheight(x); y-oht=height(y); return(y); node * rotateleft(node *x) node *y; yexrright; xrightey->left; yorlett=x: xe>htsheight(x); return(y); erin W_Data Structures and Algorithms (SPU) } node * RR(node *T) { ‘Terotateleft(T); retum(T); } node * LL(node *T) { ‘Terotateright(T)}; return(T); } node * LR(node*T) { Toleft=rotateleft(Tleft); ‘Terotateright(T); return(T); } node * RL(node*T) { ‘T-rright=rotateright(T->right); ‘Terotateleft(T); return(T); } int BF(node*T) Ih=1+T->left->ht; if(T->right==NULL) th=0; else theL+T-sright->ht; Quick Read 28 return(ih-rh) J void rebatance(node **P) { while((*p)!=NULL) {(¢p)->ht=height(*P): if(BF(*p)==2) if(BF((*p)->lef)==1) (*p)=LLC"P)s else Cp)=LRCP): else if(BF(*p)==-2) if(BF((*p)>right)==-1) (*p)=RRCP); else (*p)=RL(*p); p=&((*p)->father); } } Void insert(node**T,int x) { node**tp; node *q; Sf(*T==NULL) { (*T)=new node; (*T)->data=x; (°T)->left=NULL; (OT)->right=NULL; CT)->ht=0; (T)->father=NULL; else { pet; while(*p!=NULL) (MGCP) data 88 (*p) sr W_Data structures and Algorithms (SPPU) >left=q->right=NULL; >father=(*p); (p)>right=q; rebalance(p); break; d iffs(*p)->data && (*p)->left==NULL) {q=new nod rebalance(p); break; } iffx> (*p)->data) p=8(('p)->right); else p=8((p)-Ieft; ) } void Delete(node **tint x) {node **p,*q; pet while(*p!-NULL && (*p)->datal=x) ifGe>(*p)->data) P=&((*p)->right); else P=&((*p) left); if(*p!=NULL) {a=(*p)->father; if((*p)->left==NULL && (*p)->right==NULL) “p=NULL; else ip) lee 2 Quick Read *p=(¢p) right; else Af((p)->right==NULL) *p=(*p) left; else {node *r=*p; P=8((*p)-right); ‘while((*p)->left =NULL) P=8((*p) left); rodata=(*p) data; (tp) father; *p=C'p)>right; ) rebalance(&q); Splay Tree © Splay tree isa binary search tree, * Ina splay tree, M consecutive operations can be performed in O (M log N) time. * A single operation may require O(N) time but average time to perform M operations will need 0 (MLogN) time. * When a node is accessed, it is moved to the top through a set of operations known as splaying. Splaying technique is similar to rotation in an AVL tree, This will make the future access of the node cheaper. * Unlike AVL tree, splay trees do not have the Tequirement of storing Balance Factor of every node. This saves the space and simplifies algorithm toagreatextent. @raiTs Quick Read . 30 ies and Algorithms (SPPI ; SF _ Data Structures and Algor (sPPu) eS mtieaiees? ‘Atany poi that is the root of its sub tree and ‘There are two standard techniques of spl ; ‘Acurrent node : “middle” tree. he represented as t [ eT that are less than X, 1. Botiom up Splaying 2, Tree L stores nodes in the tre but n jot in the X's sub tree. des in the tree T that are larger than 2. Top Down Splaying Rstores no Fig. 4.12: Techniques of splaying ame X, but not in X's ‘sub tree. 1. Bottom up Splaying Initially, Xi the root of T, and L and Rare empty- Idea behind bottom up splaying is explained below : 1n below element 19 «Rotation is performed bottom up along the access | @.16 Perform splaying on the tree path, is accessed. (6 Marks) + Let X be a (non root) node on the access path at which we are rotating. a) Ifthe parent of X is the root of the tre, rotate X and the parent of X. This will be the last rotation required. b) If X has both a parent (P) and Grand parent (6) then like an AVL tree there could be four cases, These four cases are: 1. Xisaleft child and Pis aleftchild. 2. Xisaleft child and Pis right child 3, Xisa right child and Pisa left child 4. Xisa right child and Pisa right child. Top Down Splaying ‘aia When an item X is inserted as aleaf,asseries oftree | 1, rotations brings Xa the oot. These rotation are known | Empy R as splaying. A splay is also performed during searches, Empty and if an item is not found, a splay is performed on the last node on the access path. ‘+ Atop down traversal is performed to locate the leaf node, + Splaying is done using bottom up traversal. ‘+ This can be done by storing the access path, during top down traversal on a stack, Top down splaying is based on splaying on the initial traversal path. A stack is not required to save the traversal path. @GETIMO WB _Data Structures and Algorithms (SPPU) L Centre R — 2209 Ans.: Red-Black Tree Red ~ black tree is an alternative to the AVL tree. A ‘ed black tree is a binary search tree with the following coloring properties: Quick Read 1. Every node is coloured either red or black. The root is black. 3. Ifanode is red, its children must be black Every path from a node to a NULL pointer must contain the same number of black nodes. A sample red-black tree is shown in Fig, 4.14(a). Fig. 4.14(a) : A sample red black tree Red nodes are shown with double circles. Black nodes are shown with single circle. © Height ofa red black tree is at most 2 log (N + 1). © Searching ofa node can be done in logarithmic time. * Unlike AVL tree, non - recursive algorithm for various operations can be done effortlessly. Insertion of a node in a red — black tree Fig. 4.14(b) ‘The various cases in insertion with the help of the red black tree of Fig. 4.14(b). Caser {Fthe parent of the newly inserted item is black. {tthe parent ofthe newly inserted item is black then the newly inserted item is colored red. This insertion is ‘rivia. Ifthe item 38 is to be inserted in the red black ‘ee of Fig. 4.14(b) then the element 38 is coloured red, SE Structures and Algorithms (SPPU) Case If the parent of the newly inserted item ts red and the sibling of the parent is black (NULL nodes are treated as black). This will apply for insertion of 3 in the red black tre of Fig. 4.1400). Fig. 4.14(@): Zig - Zig rotation (Single rotation) Let X be the newly added leaf, P be its parent and S bbe the sibling of the parent P. G be the father of P. Xand P are red in this case. X.P,G can form either a Zig ~ Zig chain or Zig - Zag chain. Splaying can be used to handle this situation. Splaying is shown in the Fig. 4.14(c) and Fig. 4.14(2). Fig. 4.14(4) : Zig - Zig rotation (Double rotation) Case If the parent of the newly inserted item is red and the sibling ofthe parents red. This wll apply for insertion ofthe item 79 in the red black tree of Fig. 4.14(a). If the colour of $ is red in the sub tree of Fig. 4.14(a) then there is a single black node on the path from the sub tree's root to C. After rotation, there must still be only one black node. After rotation, there will be consecutive red nodes (G and 8), To colour both S and the subtree’s new root red, and G black. Ifthe great grand parent is also red then can continue the process up toward the root, until we no longer have two consecutive red nodes, Q.18. Explain with example : KD Troe, Em Quick Read 32 K-dimensional Tree dimensional tree, is a ud tree, also known as k-dimen a ie or arranging some data in a space with k sat Sojons A ked tree i a special case of binary space partitioning trees. ‘A zed search tree has the following, fone with respect is done An properties: Branching on odd level is d 4 with respect to the first key. 2, Branching on even levels is done with respect to the second key. 3, The root is arbitrarily chosen to be an odd level. ‘An example of 2-d tree is shown in the Fig. 4.15. ig. 4.15 : A sample 2-d tree Q.19 Find the OBST for the folowing data : N= 4 (We a.M4) = (o,f, read, while) ©1P2Ps 9 =(1,3.1,3) (491 AeMoqd) = (1,2,1.1,3). (Marks) + G+ P=1+142= Git a+p.=24143 G+Q+p=141eL +O +P =143435 ZX ) RQ a a 82 Yen wus? uaa cus? Wut @+Pr=44143<8 ae 1552 Gea Gag) min ((C,4*0.4(6,, +6, + min a) 2 min (64) +8=449 Ta = 2 2 eas moos ‘W_Data Structures and Algorithms (SPPU) coaete Was = Wan tq3+Ps= 641+ min fs = 2 endmarker = for (i=0; i< 26; i++) root -> data [i] = NULL; Insertion ‘A character word can be added recursively to a trie, ‘Trace the existing prefix of a word in the trie and ‘remaining characters can be added to the trie. Quick Read if (*% head —» endmarker = 1; //end of word else {head endmarker = 0; If (head > data [*x - 65] = = NULL) {head — data [*x- 65] = new trie; head = head -» data [*x- 65]; //*65 has been subtracted from x to map it to an integer location */ for (ic0 ;1< 26; i++) head — data {i] = NULL; insert (head, x+1); } Deletion Deletion of a word from trie can be implemented with the help of a stack. AAs traverse the trie to locate the word, address of ‘each node is pushed on top of the stack. Now, the chain leading to node containing the current word is deleted. void Delete (trie “head, char *x) { stacks; while (*%! ="\o’) { Spush (head — data [*x -65)) hhead = head —> data [*x ~ 65) ; xt while (1 S.empty ()) &8 chain (head = pop) delete head; } Intchain (trie * head) { n=0; atin wv Data Structures and Algorithms (SPPU) 7 Quick Read return 1; // part of chain else return 0; Function chain (), checks whether the node is part ofthe chain leading to terminal node of a trie. Q4 Whatis B tree? ans B-Trees B-tree is another very popular search tree. The node in a binary tree like AVL tree contains only one record. AVL tree is commonly stored in primary memory. In database application, where huge volume of data is handled, the search tree cannot be accommodated in primary memory. Betrees are primarily meant for secondary storage. A B-tree is a M-way tree. An M-way tree can have maximum of M children. Sey SD ES Em Cte Fig. 5.3(a) : An example of 4-way tree ‘An M-way tree contains multiple keys in a node. This leads to reduction in overall height of the tree. If a node of M-way tree holds K number of Keys then it will have K+1 children. Numbor of keys = & + Number of ways = .3(b) : An M-way tree with 3 keys and 4 children Definition AB-tree of order M is a M-way search tree with the following properties : 1. The root can have 1 to M-1 keys. 2. All nodes (except the root) have between ((M-1)/2] and M-1 keys. 3. Allleaves are at the same depth. 4. Ifanode has t number of children then it must have (t~ 1) number of keys. 5. Keys ofa node are stored in ascending order. Cite D Po Py Pp Pe Pat Po 6. Ky Ky, Ky -» Ky ae, the keys stored in the node. ‘Subtrees are pointed by Po, Py «Pre thenK,2 all keys of the subtree Po K,2all keys of the subtree Pi K,.12all keys of the subtree Py. K,.

You might also like