0% found this document useful (0 votes)
60 views

DS Akash

Uploaded by

Ritesh Kumar
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)
60 views

DS Akash

Uploaded by

Ritesh Kumar
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/ 33
STEP TOWARDS SUCCESS AKASH’S Guru Gobind Singh Indra Prastha University Series SOLVED PAPERS (PREVIOUS YEARS SOLVED QUESTION PAPERS] [B.Tech] THIRD SEMESTER, Data Structure (CIC-209) ORAL INKINS |i] BOOKS W) [Dell nll Ney NEW TOPICS ADDED FROM ACADEMIC SESSION 2022-23 THIRD SEMESTER [B.TECH] DATA STRUCTURE (CIC-209) Q.1. What is the Time - Space Trade Off in Algorithm & also explain its type. ‘Ans, Time-Space Trade-Off in Algorithms ‘A trade off is a situation where one thing increases and another thing decreases. It. is a way to solve a problem in: + Either in less time and by using more space, or « In very little space by spending a long amount of time. The best Algorithm is that which helps to solve a problem that requires less space in memory and also takes less time to generate the output. But in general, it is not always possible to achieve both of these conditions at the same time. The most common condition is an algorithm using a lookup table. This means that the answers to some ” questions for every possible value can be written down. One way of solving this problem is to write down the entire lookup table, which will let you find answers very quickly but will use a lot of space. Another way is to calculate the answers without writing down anything, which uses very little space, but might take a long time. Therefore, the more time-efficient algorithms you have, that would be less space-efficient. ‘Types of Space-Time Trade-off (a) Compressed or Uncompressed data: A space-time trade-off can be applied to the problem of data storage. If data stored is uncompressed, it takes more space but less time, But if the data is stored compressed, it takes less space but more time to run the decompression algorithm. There are many instances where it is possible to directly work with compressed data. In that case of compressed bitmap indices, where itis faster to work with compression than without compression. (b) Re-Rendering or Stored images: In this case, storing only the source and rendering it as an image would take more space but less time i.e., storing an image in the cache is faster than re-rendering but requires more space in memory. (c) Smaller code or Loop Unrolling: Smaller code occupies less space in memory but it requires high computation time that is required for jumping back to the beginning of the loop at the end of each iteration. Loop unrolling can optimize execution speed at the cost of increased binary size, It occupies more space in memory but requires less computation time. (d) Lookup tables or Recalculation: In a lookup table, an implementation can include the entire table which reduces computing time but increases the amount of memory needed. It can recalculate i.e., compute table entries as needed, increasing computing time but reducing memory requirements. Q.2. What is algorithm and why analysis of it is important? Ans. In the analysis of the algorithm, it generally focused on CPU (time) usage, Memory usage, Disk usage, and Network usage. All are important, but the most concern is about the CPU time. Be careful to differentiate between: * Performance: How much time/memory/disk/etc. is used when a program is run. 2021-3 strut LP. University-1B.Tech-Akath Books ‘Asymptotic analyia refers to computing the running time of any operation, the running time of one operation ne code we WUE vot progam aie ale matirateal unite of computation. For examp! te ay eco wets IAHR Sena yea) and may befor another operation it in computed a8 gi"), This eine ed {a competent operation running time wil increase linearly with the increase in ot ico smeane the irthing Ue of the necond operation will increase exponentially when 1 Band the corany, the running time ofboth operations willbe nearly the same if is sional complexity theory, which tigifienncly small "Ueually, the tie required by an algorithm falls under three types ~ gorithm to salve «+ Best Case ~ Minimum time required for program execution. eye goerminton of the pee ern i,t elt rc ene gg recurs TNL «+ Average Case ~ Average time required for program execution. ry anal of Ao ier gtementing ona epee «+ Worst Case ~ Maximum time roquired for program execution. «Ta predict the behavior of 2 algoeithn Asymptotic Notations ora inl mensr te sonny of an Potoving ve tne cmmealy used aymptte notations to calelate the runsing re mac mare ene 9 TOE fae eve te 8 cefan dime ule am igor slither nm can oe See ear rest Towotnmany Bn “isco +o Netation tion; itis not perfect. Big Oh Notation, O : The notation O(n) is the formal express the upper pte trol as pein J station Oi way to gree, we ca compare hemo sea On Nee Oe em case te wurtcon ins ope te Sopot anon ine an gern can posi take to compet. 1 toe impasse too ro PPO cine tn dierent peso Aigo analrss? ren tapes Algorthn Analyst ae as F000 ‘ao bear caer Def the inp for which algorithm takes lone time or wistmamy sma Bet cae Do ue elgrithm,Bxample In th inst tin nth art a ee etn rg ata thn the bet case = yore Case Deets whe egitim takes long tin or asian ee te ee the oper bad a an algorithm. Bxampl: : ee tn nat petal hea the wort ce 0c ve) Avcage cee: Inthe verge cas take al random inputs and calculate the coupon tne fra apts od tes we divide ity te ttl amber fap vragen al rand cte tine etal ease pe ciate 02s socio 4. What i the Arymptotic Analysis : Se eee sonata th Amps AlyiotAgrthme? Explain the Diftorent (O(a) = (g(a): there exists ¢> O and n, such that fin) < e.g(n): ‘Aas. Asymptotic Analysis As Omegn Notation, 2: The etaton Ge) i the mal way to expect os on Ae eee hacks depen amnion lgrinn seers to Seg Soundofa git ranting ine mare hebeat aon na glee he th Bathenatial undatifaming of runtime performance, Using asymptatic of time an algorithm can possibly take ae or the Ppa the best case average case, and worst case scenario pete co -Asyptti nai iin is onal torts tat ie ze Spt to the algorithm, considered constant, » Other than the “input” all other factors are «2021 For example, for function fs) ch that g(a) = este) for all >.) exists ¢> On both the Irwer 4) = (0) there formal way to exprest aha = jon bs The potato) the forall Ho or fellows ‘bound and the upper bound af an algerita' 4) =|) an ony) = O(n) and gl) = 4) forall n> ny} Common Asymptotie Notations Fllorngis ist of ome common esympati notations ~ constant = ‘Oa a tlog 2) near = On) abo : Oia log uaratie 5 Om) a e 1a") ianonid_[ oe ‘expnental | = LP. Univeraity-(B Tech}~Akaah Books 2021-5 QS. What is the Sparse Matrix? Explain the Array & Linked List representation of Sparse Matrix. ‘Ans. A matrix is two-dimensional data object made of m rows end n columns, therefore having total m xn values. If moet ofthe elementa ofthe matrix have O vale then ita called a sparse matrix ‘Why to uso Sparse Matrix instond of simple matrix? * Storage: There are lesser non-zero elementa than zeros and thus eeser memory ‘an be used to store only those elements, + Computing time: Computing time can be saved by logically designing a data structure traversing only non-zero elements. Example: o0s04 00570 00000 02600 Representing a sparse matrix by a 2D array leads to wastage of lots of memory ‘a zeroes in the matrix are of no use in moet ofthe cases, So, instead of storing seroce ‘with non-zero elements, we only store non-zero elements. This means staring now sere lements with triplee- (Row, Column, value). Sparse Matrix Representations can be done in many ways following are two common, representations: 1,Array representation 2. Linked lst representation, ‘Method 1: Using Arrays: 2D array is used to represent a sparse matrix in which there are three rows named as + Row: Index ofrow, where non-zero element is located. * Column: Index of column, where non-zero element is located ‘+ Value: Value ofthe non sero element located at index -(row, column) oosoa Ro ]°]]2] 4] 8] e 00570 => [eam [2] 4]2 ya faa oo000 vee [8/48 )7/ 2] 6 02600 Method 2: Using Linked List: In = for falda ervastentee ‘inked list, each node has four fields. These * Row: Index of row, where non-zero element is located * Column: Index of ealumn, where non-zero element is located * Value: Value ofthe non zero element located at index ~ (row column) + Next node: Address ofthe next node 2021 oe roast eee intent tn a eae os tn st set using Union operation. . single di “eng it sets ton ince i oo. Fading repeseataiv ofa dint eet Ghnckf oer dii Bere CA Tien with a namie of erent permed on hes pate nee enh reatn, a Pm piachingbe tat ag tdbeor indie i lain iad inal (irc ond end) nt et an wich abet pra leat en Ti cn be wed fr detrning te dents ae tes be mcuaen a neato int single eve Hore at wo have to check f the roca tors tay, thn we ant perform wien 7 Whats the Polynomial? ; . ‘pach agai nth epetson in varible = which i inthe fora es Parr where aco kala th calor fel numbers and ear meittenttn tad dere plmami “Ko enna chara th plait each term in the polyno exyenion ot pate oon coicent + other ithe exponent Sepia 10s 2, hr 10 and 26rd 2, iit exponential vale. Pinto hepin Min wile wring with Peyomials: 1 The sof ch cet nd ens slred within th fice abe * Additional terms having equal exponent is possible one nd dere tlt fecha the polynomial must be done in acest 8. How to representa Palynomi pecemes the fiend of nother person LLP. Universty-{B,Tech}-Akash Books 2021-7 ‘Ans. Psiyomil can be ropretnted inthe various way. These are: By the ws ofarraye + By the woof inked List, Representation of Polynomials Using Arrays ‘There may arse some station where you need to evaluate many polynomial cexyreions en perform basic arthmeti operations ike edition and eubtreton with {ne mambo Forth, you wil veto getaway to eprenent thee pelyanaal The tiple way isto oprseat a polynomial wit degre snd stor te cefient of nl terme ofthe polyoomial nthe area. So avery array element wil consi of te values * Cocfien and * Exponent Polynomial representation using inked List ‘The linked lit can be used to representa polynomial of any degree. Simply the soformation feldia changed acordngts the number of variables edn the ply, Ifa single variable is wed inthe polynomial the information fel ofthe nove Contains for cofcent of variable and the other for dogree of variable, Lat us tne pea ‘ousldoran example treprenn a polyoma! sng Heke tos llow Paynmmial. Seay 2e-8 Linked List r09r GE pal} GG In the shove linked is the external pointer ROOT point othe st nade ofthe lnkad it.The rat node ofthe inked li contains tho fformaton abou he variable ‘ithe highest epee, The frst ode nt othe next ne the wer Saget OF the vanable Representation of polyomil using the linked list is beneficial when the perationson the paloma ike addition nsubtractons are performed, Therenling olyaominl can ls be traverse very eel to play the pagauaal T ali ~2T +GbO-GER oor Lan -6oT-GE The shove two linked ist represent 80 = Ae Be — 9 and Sc'— 2+ Ge + 3 respectively, Iboth the polynomials are added then the reeling linked wi be: oor | ap oh = ‘he linked list pointer ROOT gives the representation for palynomil, (8x?— Gx!+ 8x - 6. = TERM E. DCE FIRST ISTER (B.TECH) [ETCS-209] a UCTURES—SEPT- 2014 2% sting Quon NA TH comp Define - its type’ ci iquonet Wat ees TEA {Q.L(6) Defines Dowdle net ca nee ed ern ‘Aas: Adoni i ad ist negate ee sane? jt a oboe a) nt arb ae Tor | See eet 29 es a w ae cee ees ee Sasicall are two variants of double-ended queue. me inne niuimtaecette at ee deletions ean be done only at na 7 cana ata ee 4. Wat ae ie i ol etn oft en called ole, Te Cn ns ar ee area ‘The data fed contains an actual value to be stored and processed. And the link field contain the address ofthe next data item in the linked list. (star neo] [nro] x Single linked list ee pee] neo|warfefrer [ne [roe kf rev | me le Te Doubly linked list a 22014 ‘Third Semester, Data Structures ‘Types of linked list (2) Singly linked Ibst (@) Doubly linked Sst (6) Cireular linked list @)Cireular doubly inked list Q.1.(c) Reverse linked list without using the pointer? ‘Ans. To reverse a linear linked let, throe pointer fields are used. These are tpt, ptr, cept which hold the address of the previous node, current node and next node. To basin ‘withthe address ofthe first node, which is held in pointer variable FIRST, is assigned to PIR and typt is assigned value NULL. ‘Alport Step 1 PIR FIRST Step 2 ‘Wer = NULL Step 3 Repeat step 4 while PTR! = NULL Step $ (@) CPT = LINK PTR) (Q)LINK PTR) = TPT (TPT =PTR (@ PTR =CPr Stop 5 stor. Q.1.a)(#) Convert the following in ix expression into a postfix usinga stack. la+(b-o)l* (de +¢-h} Ans. ‘Symbol Scanned | Stack Express (Postfi) 1 ‘ { a 2 a t a 3 + be | a 4 & ab 6. > ay ab 6 - He abe 1. Be abe 8 ) be abe o. ! abe~ + 10. . * abe~ + u, ‘ * abe— + 12. i MC abe~ + 8 4 “1 abe~ +d 14 = He abew+d 15. e se abe~+ de 16, ) * abe + de ~ v1. ' w abe—+ do~ 18, ( m abe —+de— 18. 6 H abe~+de-f 20, + os abe—+de—f 21 e whe abe—+ de—fi abe + defi abe=#de=fih—+ . be + de—feh-+/* eee t “Ans We use the vid pointer tmp ! a ‘ecerogenoa inked lit contain ilerent datatypes i its nodes and we need a ink, ‘ointer te connect them. Since we can use ordinary pointer fr this, we use th tr Vid ante is geen itr type, and capable fring pointe fo any tps. ‘@.L(e) What are thresded binary Trees? How are threads different from ‘pointers? And hew we oun determing tho next node tn which a thread points? ‘Ana. In linked representation of any binary tre, halfof the entries in the pointer field LEFT and RIGHT wil contain null entries. This space may be more eficictly ‘sed by replacing the all entries by special pointes called threads, Which pints to ‘he nodes higher nthe trees. Such tees are called Threaded Tree. Ditference between threads and pointer: Threads in a binary treo must be istinguished from normal pointer. Ina graphical representation of threaded binary tree, threads are chown by dotted lines. In computer memory, an exira el called tag or flag ie used to distinguish a thread from anormal pointer. ‘Tree can be threaded using one way threading or two way threading. In aone way threading, ¢ thread will appear inthe right field ofthe node and will point to the sucesor node in the in order raversl of tre; and in two way threading of tree a thread vill also appear in the eft field of node and wil point tthe preceding node inthe in onder traversal of tree 21a) Write an algorithm or psoudo code to extract characters from a given ‘ting from a given position fora characters and store{t another string which is {initialized atrun time. ‘Ans. include | define SIZE 100 ‘oid print. st (char 8; void read str (char 8() main) ( char ote (SIZE; dt read ate (Ste); rint_str (Str), | while Str (0); +2014 ‘Third Semester, Data Structures , Void print.str(char*S) ‘ int for = 0; 8(i}i44) putchar (iD; putchar (\n), 1 Q.2.() What is Abstract Data type and its implementation through data structures? ‘Ans. Abstract Data Type: Abstract datatype is the apecifications ofthe datatype which specifies the logical and mathematical model of the delta type. ‘To implement a fraction data type: ‘Type day strict | int numerator, denomination; fraction; ) main 0 fi fraction f numerator = 1; £ denomination ‘Aarieton | <—use te ADT t [Seecticaton] «define te ADT remeriatonft— implement ADT When we we abtract at pe; our program dvd note ‘The Application: Th pr ha use Abtract ala pe ‘The Implementation: The pat tat npn the sbatract datatype, 200 How willyou check the validity ofan expression contlaing nested parenthesis? ‘Ang. To chek the validity of n expression containing nested parenthesis we use the tack Stack wrk ef hs The sap se. _ (Maintain a stack of charactors, @ Whenever you ind opening braces, for pushiton the stack (9) Whenever you find cloning traces, hack tap of stack corresponding opening brake, ifs then pop th stack, sls trek the loop and searn fe (@) Repeat step 2-9 until end ofthe sring. (a) Writenpaoudocodelalgorthm for ( insertion atthe end ofa circular linked list. (4 Deletion ota node with agiven data ina doubly Linked ist Ans, FIRST ‘0 HL Lhe i ee, 5 PTR cer Lp University B.Tech)-Akash Books 20165 pepeat CPT = Link CPD ti tink (CPD # FIRST LINK CPT) =PTR = FIRST LINK PTR) = F _ sheet “IfAvail = NULL then linked list is overflow and STOP. 2 me ata Sao UN AAD ad POT 3 orn = FST {get ep hil LINK (PD) = FIRST Scr ume © innwlern Winelude ‘Struct node (int data; struct node * next; % Void remove Duplicates (Struct node * head) t Struct node * current = head; Struct node next — next; if (Current == NULL) return; While (Current > next! = NULL) i current —> next> data) if Carrot 7 data ( next next =current ~>next~> next; free (current _ next); void Push (Struct node ** head ref, int new-data) t Struct node * new_node = (Struct node*) malloc (size of (Struct node)); ‘new_node—> noxt = *head-re); (thead-ref =new-node; 1 ‘Void printlist (Struct node * node) C While (node! = NULL) fl printf((/a", node -> data); ‘node = node ~> next; 1 20%, sy e-2014 ‘Third Semester, Data Structures (i) Ais deleted (dit) D & Bare inserted. (en : wd depts enor: vested . ' ; dv) B& C deleted. 6:10) whose base adden, 7 1 @-4(0) Consider a float array APR (2 00 finde eden APH G8 ime atmcrestcke 1 ‘mba eas etAPR ae (cegsre? rleedel=6 Iyx0-64126 iat Acordingy PR cannes ty lye 606 210 lament, ae Suef propamning ingag ae APR Samy a7 mejor ode ang aes sue = 92d wr per ene ta Teeth ote mee re : Brecaed Beel-cded Byrd O02. For row major order, we have: Bl, = 3x6=18 t t “a ee § 18+3=21 @Ly+B)Ly = 21x5- 105 leted. (Eyly+B)L,+B, = 105+2= 107 (op Pied tsar 1813004 oT 0 +4968, Consider a ezcular queue wi aoe llowing sperations sired § Position. Find the value of a AB. Gimered i) Aisdeleted. (i) D&Bareinserted. (is) BAC deleted. ! l cot Eimeria. (ci) Deleted, a = ii) G& Hinerted. ‘Ans (DA,B.C, inserted, G8 Hinserted. Taare t ‘tid Semester, Data Structures 2014 : (98. Write short notes on any two ofthe following: (e) Bucket Hasing rectyin the hash table- Each record wity As. loved hashing stores erat) The lt computed by hagh ‘aloe value K, has a bome position cas 8 available space ty “en a reads inserted, the bucket which is mapper any 28st (ies teh ret ‘nodes are 1, 2,8, 4,5 the BST will look like + 41. (&) Céustruct Binary troe'T from following sequence. PREORDER:ABDGCEHIF INORDER:DGBAHEICF Ans. PREORDER:ABDGCEHIF : INORDER:DGBAHEICF @ ®@ ® © & © Qo O ‘ QL. (c) Number of nodes in complete tree is 1000000. Find its depth. (1) Ans. The depth of complete binary tree is log(n) where no of nodes isn. So the depth of complete binary tree which has the 1000000 nodes is. Jog (1000000) = 6 Q.1. @) Write algorithm/programto perform POP operation on stack using singly linked list. @ Structure er, Data ‘Third Semen 2-015 ‘Ans. Vid peP(©) ( Sic node" op == NUL) teint Undertow? return: 1 poet: top ptr inks fe pe 1 or _ seereon ground header linked list and cireulgs Oe 4) header inked is? ; “tne A pounded header lit isa header ist bere the last node contains the muy reiter “Acar bade ists a bear lst where the last node points back othe headey ode ‘QL. (? What isthe condition that a cixeular queue is full if the queue ig ‘implemented using arrays? a ‘Ans. If (front ==0)&& (ear == Max 1) (front that means queve is overdo or fil QL. @ Binary tree withN nodes has exactly wuuasNull branches (1) Ans Binary tree with N nodes has exacty n +1 null branches. 1. Ch) What is Time Space Trade off? sy alia Time Space radcofl Isa wavofsving a problem ealevlation in les tine hy using more space (or memory, or byelving a problem in very litle space by spending long ime. Most computers havea large amount of space but not infinite space. Also, ‘most people ae willing to wait litle while for aig eleulation, but not forever, Sot pe apltm staking along tine bt not much memory, a space-time tradeot would ju use more memory and solve the problem more quickly or it could be 7 quickly or it could be solved very sean a emery hanyou buen try tospend more time solving 2. (0) i G2 G) Why height balancing trees required? Create AVL tree of following BEB OR def nf a rear +1)) Creation of AVL Thee Nodes: 02,83 6.5 deaf LLP. University-[B:Tech,}-Akash Books 2015-3 Insert @ @ m~ & @ Inserts yo" & ‘hore ie Balance factor ofa in-20 after RL rotation the re is. we nd es @ @ a" Go Insert Teri the Balance far of is~ 20 after L-R rotation the tree is @ "6 me LP. University-{B Tech }-Akash Books 2015-5 ‘After Insertion of w the Balance factor is unbalanced so after applying the I-R rotation the tre is— Inserte After Insertion of node e the tree is unbalanced so after applying the J oe spplying the I-L rotation @ Inserto Data Strveture ane afer APIO PLR rota, LP University {Teh -Akass Bonk 2015-7 (o LINK (PT = TPT (TPT = PTR (a) PrR = OPT ‘tap 6 Stop 3. (a) Consider tho following in fix expression and convert into reverse polish notatlon using stack. 6 ‘Ans, (A+ (B*C-(DIEAE)*O)"H) sted See 18 je unba snr venice ABC* DEF A/G* ~ ABC* DEF A/G* ~ ARC*DEFA/G*=H*+ ic DEF Nes Character Seanned qi A nwert + ( B B . AB t ABC 5 ABC | ABC D ABC*D | i ABC *D. | E ABC * DE a ABC * DE F ‘ABC * DEF ‘fer Insert the node fhe tree is unbalanced so after apply the RL rotation the ) ‘ABC* DEF * final eee is . ‘ABC* DEF 4/ @ ABC* DEF A/G ) ABC* DEF */G*— H ) Reverse polish notation ‘Q3. () What is an algorithm/program for inserting and deleting anode ata sven location in circular linked list. © ‘Ans, Inserting a node at given location. 2 () Writea procedureiprogram to reverse: Step 1, _IfAVAIL = NULL then write overflow and stop ‘any more memory? eee ‘Step 2 Read DATA as information of node after which insertion will be made, ‘Ans, Reverse singly linked list, Step 3, PTR = AVAIL Sep. 7m« ast AVAIL = LINK (AVAIL) Sep 2777 NUL, Read Info (PTR) 9 Repeat step 4 while PTR! « NULL Step 4. CPT = FIRST Step 4(a) OPP = LINK (PTR) ‘Stop 5. Repeat Step 6 while Info (CPT) ! = DATA 2015 Sup 6 Step 7 sop 8, St on Dactnotonde st ren AT yan top Step 1 FIRST NUT Tyan ofroetobe deleted. Step 2 ee Sep3. PTR nfo PTR) # DATA Step 4. Repeat step 5 while info ( Seps. CPT=PTR PIs LINK PTE) LINK (CPT) = LINK PTR) LINK (PTR) = AVAIL, AVAIL = PTR Step. Stop. Qe seppnemetinensonalrayAand Bare sarod A.29 a9 and B (8, 68,105) stored in columa major order. (0 Find the length ofeach dimensions of Aand B. (Gi) The number of elements in Aand B. i) (ii) Consider the elements BG, 3) inB. Find the effective indices E1, Serene oe words per memory location, (25) ‘Ans. i) The length of dimension is obtained by “Length = upper bound -Lower bound +1 Heace the length Lio the dimensions of Aare: U1 =2-(-2)+1=Sand12=22-241=21 Lh =8-16128,1205-(5)41411,195-(10)4 1216 { Accordogly has 521 = 106 elements and B has 8*11°16 = 1408 elements, (iy Th etctive index Biisbtaned where Kits i and LB is the lower bound. a UB. where lls the given index fee Bh 3-122,2209-()aBb=9-(10)=19 Zonsidering Bis stored in column maj . calcalted an" * *ev*d i olamn-major onder, the addroes of B (3,2) wil be sup 6 ‘Step 7. sy 1206, (2 + E2) 11 + Bt = 1208 4 2 aan eres of 183.3 «400 +4421 an + apo 408) What is Garbage Collectonst = Ans. Gabage Collection: tuna eet Cathe aleston 66) ag dynamic approsch to MeO tr cna beep allocation that proseseenseen ents dnd 210 LP. University-[B.Tech,}-Akash Books 2015-9 4. (@) Write algorithm/program for insertion operation on quoue using ‘ingly linked list. ‘Ans. vwidinsert 0 ql struct nde * pt; : pix = (atruct node * malloc (size of(truct node) int item; prinf Input the element for Inserting”); NATION [NOV.-2015) R [B. TECH] [ETCS-209] Mm, eyo morequeton, % cnsBeiet : llofth index nodes; in all "ee ony, % ween B- (a) iterenee nr painters vinted ‘a sequential file ar a ABE grt is yen ong italy, nes ease, 1538 0065, ee tf, 18 752 3 way Search tree. [e[*] Pl Q1.(€) Consider the following specification of a graph. VG) = 11, 2,8, 4, 5} and EG) = (1,2, (1,8), (3,3), 4, 4, D, (4, 8), 6,2) [ols [Ea — » | 3 | 90 Draw itsadjaceney matrix. @ ‘Ans. VG) =(1,2,9,4,5) BEG) =, 2}, (3), 9 (8,4 0, 4,8), (5,2 ‘Ajaconcy Matrix Representation. Tress Torro} 2]00000 300110 4 ooo1 slor000 21. @ Compare the complexities in average ease and worst case of! following sorting: ‘Merge sort, Heap sort, Quick sort, Selection sort LP. University-(B Tech. }-Akash Books 2015-11 ns Seo [eae] — Nog Noa Merge Sort Nog Nilo Nog Heap Sort Nog Nog Nog Selection Sort | Nt ¥ ™ Q1. (e) What is psoudorandom hi ‘Ans, Pscudorandom Hashing ‘Acommon random-number generatoris shown below. : ye arte ‘To use the pseudorandom-number generator as a hasing method, we set x to the ‘oy, multiply it by the coefficient a, and then add the constant e. The result is then ing method? ¥ = (Tx 129267) modulo 307 Y¥ = (2061589 + 7) modulo 307 ¥ = 2061546 yea Q2.(a) Construct B-TREE of order 5 by inserting the following elements. 3, 14,7, 1,8,5, 11,1, 13, 6,23, 12,20, 26, 4, 16, 18, 24, 25 and 19. And also delete values 6,23, 8 from above constructed tree, Ans. BoTree of order 5; Blements: 3, 14,7, 1,8, 5, 1,17, 13, 6,28, 12,20, 26,4, 16, 18, 24,25, 19 Insert 3 3 Insert 14 ENE Insert 7 ap Insert 1 tea 7 Insert 8 TP a] Here node was already ful 50 after insert 8 itis splitted into 2 node and Tis the median key. z Insert 5 aT LP. University-(8/ech.J-Akash Books 2015-13 Here node was already full so after Insert 19 tis splitted, into 2 nodes. 17 isthe ‘median key 60 it will go into parent node. Here perent node is already ful, oo itis splitted in 2 nodes and 13 i the median key and it will beoome the new root. ‘After delete the node 6 7Le wa 2] [e[as [28] GGHoe) ffs) Here node was already fl siti oplited into 2 nodes and 20 is the median ky Here nade was alzeady fll o after Insert 4, Its splitted into 2 nodes and 4is the Insert 16,18, 24,25 After delete the node 8 GET) Tis) [efi] [2a] 2s] 25] Q2.(6) Write algorithn/program of depth first search for traversal of graph? ‘Ans. Step I: Set status = 1 (ready state) for each node in G. ‘Step 2 Push the starting node Aon the stack and set its status = 2 (writing state), ‘Step 3: Repeat steps 4 and 5 until stack is empty Stop 4: Pop the top Node N. Process it and set its status (processed state) ‘Step 5 : Push on to the stack al the neighbour of N that are in the ready state (orhose status = 1) and set their status = 2 (waiting state). Step 6: Exit, 3. (a) Suppose the table T has 11 memeory locations T {1}, T12}..TU1) and suppose the File F consist of records A, B, C,D, E,X, ¥, Record: A,B, C,D, 2,X, ¥,Z and its hash address U0: 4, 8, 2,11 4, 1, 5, resp. How file F will ‘appear in memory when 8 records are entered into table Tin above order using linear probing and quadratic probing collision resolution technique? Find average successful search probes (S) and average unsuccessful search probes (S) and average unsuccessful search probes (U) also for both? @ ‘Ans. Rod 4 BO BR & YX 2 oof eee te Suppose the 8 records are entered into the table T in above order using the liner probing and Quadratie probing collision resolution technique then the file F will appear ‘inmemory as follows. Men 5 0 8 AUER Y Address: 1, 2 3, 4, 5, 6 D _ Data Structure sri Senet a a anh me ee ny gh 8 ten ed won apt heat a sorts emer i8 7) syocessful search follows: Si rage 0. SP retelels2e2e0e9 a Bore a atpets assent nr allows The seerage =e. TH645444+3424142614159 tc ie! - 1.38, oi vahotb crs and ee a ee reach ofthe lation, me ree internal sorting and external sorting? Sony. ene 178504485. aa nal sorting: Which deals wit sorting the data stored in compusey one ec re Se aia ering he a aed i le. Eee rT et une meme Brann Phe saw he rt, 2,7, 2,654485 tthe =? ‘The rst sum ads ad the no. of probes ‘Q3.@) Difference bet PRESCIE T T =] Output of pass 1is input to pass 2 and distance = 1 z[e[s[ [a |e a a [nye Output of pase 2is =[«[s]e [we digit employee number ereany With 68 employee, Each has been assigned a4 her which has been assigned a 4 digit employee number fmeng sa eacompany's employee file, Suppose Lb ~98.Then mae nsist of 100 two digit addresses 00,01 Prange eld sing rime no, lest too mid ea : to find oat : following employe ne. 2614, ay vsoat sit hash address for exch of LP. Universty-(B Tech, Akath Books 2015-15 ‘Ans. (0 Division Method: Choose a prime na M close to 99, uch as M = 97 Then. 1H (9614) = 11, (6882) = 62 H (1825) = 79 ‘Thatis dividing 9614 by 97 gives a remainder 11. dividing 6842 by 97 gives a remainder {62 and so on. In the case that the memory address begin with 01 rather than 00, we choose thatthe function H(k) =e (mod M) + 1 to obtain 1H (614) = 11 +1 = 12, H (6882) = 62-+ 1 = 69 H (1825) =79 + 1=80 i Midsquare Method: K 9614 5882 1825 ® 92428996 saso7924 3330625, He) 28 97 06 Observe 4% and 5% digit are choosen for Hash address. (did Folding Method: Choping the keys K into 1,2, 1 digits and add them. So the _adaress willbe: H(9614)=9461+4=74 1H (6882) = 5 +88+2=95 (825) =1482+5=68 4. (b) Write algorithmprogram of anyone sorting technique which is used ‘when input elements are small? Difference between comparison based sorting ‘and non-comparison based sorting? on ‘Ans. When Input elements are small then many sorting techniques may be used such as, bubble, sort, insertion sort, selection sort et Algorithm of Selection Sort Lenslength [Al 2.Forj=lton-1 3. emallest 4.fori=j+ ton 5. IfAli) ‘Third Semester, Data Structure 22016 1.0 Number af nodes in complete toe is 10000, Find its depth? (2 wx Te depth fps inary wil where o.ofodes tn. So the dept cteonlt tiny re whic as the 100000 neers ag 0000) = 6 2.(o Weitea progranialgorithm to evaluate postfix expression using stack? Conaider the following taf expression and convert into posts ‘preston using sack (A+ OC~D\E"FO"D ab : ab ° abe - abet f c abet | a abetd I 4 aberd e abetde | * abetde f abe*def ) abetdef/ « ) + abetdet*/g* ‘ ” abetdet"/g*- h ” abetdef*g*-h ) abetdef"ygt-ht+ ‘@1. (6) Whatis the maximum height of any AVL trees with 7 nodes? Assuming height is 0for a tree with single node. @ ‘Ans, The maximum height of any AVL-tree with 7 nodes is 8, AVL trees are binary trees with the following restrictions, 1 the height difference ofthe children is at most 1, 2)both children are AVL trees 22017 "i ems ae Tiny tee te ree Sone rae eee 7 agen Sia comida ie Ca on sorters mgutions a ee et ees een ane eee ertebteen es eer rae ree aaea pet bp og eon eee Pear ere 2 tree data structure, the total number of egdes from leaf Gv) Hetght of tree ‘bods to» particular node inthe longest path is called as HEIGHT of that Node. 102 LP. Universty-(2.Tecs}-Aleaah Books 20s dre, ight of he rot des ad be hekght ofthe tee In.atree, ekg of allot Q2.Attempt all parts: Q2.(a) Caleulate the address of clement at X14, 3} ina 2D array XUSI0AI stored in a row major order. Assume the base address to be 1000 and each (clement requires 4 words of storage. o ‘Ans. Row Major Order LOCIAG §) = Base (A) + win i — Lower bord for rom inde) + —lomer bond for column index) Base X= 1000, =4,n=4 So the address ofX 4.5) =1000+414(4~ 1) +(8—1) ($1000 + 404 43 + 2) = 1000 + 4 14 = 1056. 22.6) Write analgorithm to delete thelast node of thelinkedlist. (5) ‘Ans. Step I: Iflinked list s empty (START — NULL) Write “Sorry Buddy there is no node ‘Step 2: If linked list have only one node (START > NEXT-—= NULL) froo(START) ‘START = NULL ‘Step 3: If the list have more than one node PIR ~ START while(PTR-> NEXT != NULL) t PREPTR = PTR PTR =PTR->NEXT 1 ‘PREPTR-> NEXT = NULL free PTE) Step 4: EXIT @2.Attempt all parts: @3.(a) Consider the following circular queue with a storage size 6. FRONT =2, REAR =4, QUEUE:_,LMN_. Describe the quoue as following operations takes place: LAdd 0 2.AddP 3.Delete two elements 4.Ad4Q,2,8 5.Deleteone. (3) (3+7=10) LP Unni. hah oka peice — eset \ bey neal Faso és t 5 9 (I i . rt Insert G Q coaeensnne 5 4 5 ° © : O é ® © » a 2017-5 | | Rew. Insert T GAR B&B R s N ° P é gd beat 9 (0) Dl oe ter ee ee 6 oul “| ale J ! 3. as thea a 1 Sinemet in alphabetical ordarintoanens| Hert TR OREMREA RG " final oy 2.Find the post-order traversal of? a Inser:P Insert A Insert P 9 @ ad Insert Q : 5 ‘This is final tre 7 © ® @ (Gost order traversal of tree Tig © [AFEHGDQPMTRG 66 & Q4.Attompt al parts: 4 (o) Abinary tree has 9 nodes. The inorder Preorder traversal are \, of yield the following sequences ot nodes o ® INORDER:EACKFHDBG PREORDER: FAEK CD HGR. Draw the treet, ‘Ans. INORDER: EACKFHDBG PREORDER: FAEKCDHGR fe EAck] [Hea] PA to p ° e OBS w Hoss | ©) Lex © » ‘This is final tree T. pata Stott LP. Universi ued Oe fllowing clements arg -— a pes Feseeag | sort ae order: 15,14 anil of 3214 ps ae sett g 2017-9 4 4 after Rel Insert 16 ‘After Rebalancing Insert 15 END TERM EXAMINATION {DEC. 2017 THIRD SEMESTER [B.TECH DATA STRUCTURES [ETCS-209] oe ; : MM.:75 eg an fie us lg Ne 1, Mh amps Set 1. (a) ‘what is an Abstract Data Type (ADT)? on abstract Data Types aot Data type (ADT) is type (or cass for objects whose behavior is defined wots ‘and a set of operations. * 78 pe defniton of ADT only mentions what operations are to be performed but not sorte operate ile nplemened It doesnot specify how data wil be organized sor raha rts wb ued inplenaig thre Gt pocause it gives an implementation independent view. The process of providing ‘ay the essentials and hhiding the details is known as abstraction. te user of datatype neod not know that datatype is implemented, for example, gebave been using ink float, char data types only with the knowledge with values that vote and operations tht can be performed on them without any idea of how these ‘are implemented. So ‘a user only needs to know what a data type can do but not pow it will do it. ‘We can think of ADT as ‘a black box which hides the inner structure and design of he data type. Now Well define three ADTs namely List ADT, Stack ADT, Queue APT Q1- (6) What isa self-referential structure? @5) ‘Ans. Aself referential structure is used to create data structures like linked lists, stacks, ete, Following is ‘an example of this kind of structure: struct struct name | A datatype datatypename; structname * pointer_name; k Aself- Jerontal structures one ofthe data structures which refer tothe pointer to (points) to another structure of the same type. ‘For.example, a linked list is supposed to: beaself-referential data structure. ‘The next node of a node is being ‘pointed, which is of ‘the same struct type. For example, typedef struct listnode { void data; struct listnode *next; }linked_list; Inthe above example, the listode's@ is of the type struct listnode. selfreferontal structure ~ because the *next ated olde at 3 So the nex probe is comps Norte (50g 2 Sy, 1) = (4087 + 1} 087 =@+1)mod T=4 ttn pane ‘H (430, 2) = (40%7 + 2°] mod 7 204+4)%7=0 ‘Now (320) ellie tO. othe next probe is 1690, 1)=1 Here T [1] isnot fre. Hm, again T (4) isnot free 1H (5920, )=2 Iti free. FIRST TERM EXAMINATION [SEP. 2018] THIRD SEMESTER [B.TECH] DATA STRUCTURES [ETCS-209] Time: 1.6hrs, Noté:Q. No, 1is compulsory. Atempt any two more Questions from the rest QL Attempt all parts: (a) Caleulate the postfix expression using stack also demonstrate the steps. (2) 5,3,+8,2,—" M.M.:30 io SymbolSeanned | Stack . 3 "63 8 (5+5)(A=3,B=5) 38 | 88,2 a6 (8-21A=2,B-8) 48 [8 61A=6,B=8) @.1.) What do you understand by the term spacetime tradeoff? @) ‘Ans, TimeSpace tradeott Is away of sclvinga problem calculation es time tnyusing more space (or memery, or by solving problem in very ite spacey spending along time. Most computers have a large'amount of space, but not infinite space. Also, ‘most people are willing to wait le while for a big caleulation, but not forever. So if your problem staking along time bt not much memory, a space-time tradeoff would Jetyou use more memory and solve the problem more quickly oritcou be solved very ‘quickly but requires more memory than you have, you can try to spend more time solving the problem in the limited memory. ‘Operation BopA) @.1.(€) Differentiate betiveen arrays and linked lists. ® Ans. . ‘ARRAY TINKEDLIST 4 Tray i collection ofelement of mar | Linked List isan ordered collection oF datatype elements of same type, which are conned to eachother sing pointer ‘ray supports Random Ace Linked List supports Sequential Access, Tan array, elements are sloredin Tha inked list, new elements canbe contiguous memory location or stored anywhere in the memary. consecutive manner in the memory. Inarray, Insertion and Deletion operation | Insertion and Deletion operations takes more time, as the memory locations | are fast in linked list. aroconseeutive and fixed. | Memor locat yn 8s ‘Memory is allocated at runtime, as anc Ee aca ‘when a new node is added. It’s also known! is declared, at compile time. It's also " cores used in FO a evecare the nae which dees act have g Be pestis exode with xo child, (nigh of ee sae dar race Se al ame chops em eat a pecan sen Se nga ps net = HOGAN afte Node In tree beige PAT oe eg ete tee ee Betg ht ofall eat nodes 2 seem al parte 1: Eaplnin erene ype fed o ae Types of inka Liv Tere a? Stren iemectations of Linked List Bs Sy Link ine: Se i oc ee ss wie tare ata pss elie aiden parte 2 es ts es tse fn. Tie peecins vee pecorn se uoiy ‘oie Ys wei i adr insertion, deletion 22d LP. University {B-Techi-Akash Books 218s Doubly Linked List: In doubly linked list, each node contains a data par: and eo.ddresses, one for the previous node and one for the next node. | ow | 2 2» r Per ap Net Pv Om Met Pov an Net Circular ed List Ia cralar linked lit the last nade of the Et lds the dren ofthe fest code bce forming acral Chas. ar on me comet ee on oe Ie Fist 12h i tent Lees ee (2.0) Write am slgorito to delete the second last node ofa donbiy Hake me o Ane prs ‘while(ptrorptorpt! = NULL) a eros Renn Perorpeolpt=pre; freetpere Q.3.Attempt all parts (a) Write the algorithms for PUSH and POP operations in stack o Ans. Pash Operation: The proces of putting'a new data clement anto stack is known oc 2 Posh Operation. Pash operation invalves a series of stops + Stop 1 — Checks ifthe stacks fall + Step 2— Hf the sacks full, prodaces an error and exit + StepS~Hf the sack is ot full, inerements top to point next expty space. Step 4— Adds data clement tothe stack location, where top is painting. + Step 5 — Returns success. ‘Pop Operation: ceasing the content while removing it from the stack is Known ss Pop Operation. A Pop eperstion may invalve the flowing steps + Step 1 Checks ifthe stack is expty. + Step 2-1 the tsck is empsy, produces an ror and exit. + Step 3— If the sack is not empty, seceases the data element at which top is veintiog ‘Step 4 Decreases the value of tp by 1 + Step 5 ~ Berurns success, y | LP. University-(B.Tech}-Akash Books 2018-5 @ (0) Insert H ® © ® Q Invert P ® Yom SF @O Q Insert > Q @ QQ (9) OD © Ow ® mee eo § BO Inorder Transversal of above tree is: ABEFGHDJMPRZ ‘This is final tree T ations in AVL tree with the help of erent peso © oe ean ie 1H mnen tati b ee perform the following four kinds of rotations. Q Q*) : q@ > ao ® © © © © Ft sioner tee — 0 LttReaten LP. University-[B Tech}-Akash Boks 2018-7 LL Rotation: AVL tree may become unbalanced, ia nde is inserted in the left subtree ofthe left subtree. The tree then needs a right rotation 2, (c 1 > oN So ee ee L-R Rotation: Double rotations are slightly complex version of aliready explained version of rotations. Tb understand them beter, we should take note ofeach action performed while rotation. Lat first check how to perform Left-Righ rotation. Ale®- ‘ght rotation is combination of lt rotation followed by right rotation ‘Action ‘Anode hasbeen inserted ita the right subtree of the left subtree. This makes C 22 “nbalanced node. These scenarios ease AVL ‘tree to perform left-right rotation. “ ‘We first perform the let rotation on the eft subireeofC. his makes A, the lft subtree of B. o Node Cis il unbalanced, however nov itis Wy because ofthelet-subtre ofthe let-sbire. of “o We shall now right-rotate the tree, ‘making B the new root node of this ‘subtree, C now becomes the right subtree of its own left subtree, senna ei8 ° ; ese olned a sgh- Left Rota a & 4 sention echt Lt Rotation, ig \ ope of 3 ion. pea moan: Te me Tt ot eage ‘ation sere into the eft ut “ Anode bat netic makes Aan A tin inode with lane factor 2 Ma . ® sora the right rotation Fis ode, making C the right subtree of sag eh eabtee B. Now, B becomes the right subtree af A. Node Ais stil unbalanced because ofthe fighter ofits right subtree and requires sa tton ‘Aleftrotation is performed by making B the ‘ew root node of the subtree. A becomes the left subtroe ofits right subtree B. ‘The tree is now balanced, END TERM EXAMINATION [NOV-DEC 2018] THIRD SEMESTER [B.TECH] DATA STRUCTURES [ETCS-209] ‘Time:8 hrs. MM.:75 (Note: Attempt ony five question including Q No I whch i comple Selec one qaetion rom each unit QL. Attempt al: (@) Whatis bucket Hashing? as Ans. Hash buckets are used to apportion data items for sorting or lookup purposes ‘The aim ofthis work is to weaken the linked lists 90 that aearching for a specific item ‘can be accessed within a shorter timeframe. key ash Function eocet rare Mark Bat Tae ohn Reese —_ | ce ame Miche Cri 2 ‘Anash table that uses buckets is actualy a combination ofan array and a linked st Bash clementin the aray tho hach ables tear fer ied iat All Gememst that hash into the same location willbe stored in the ist. ‘The hash function assigns each record to the first slot within one ofthe buckets. Ia case the slot is occupied, then the bucket slots will be searched sequentially until an open slot i found. Incase a bucket is completely ful, the record will get stored in an overflow bucket infinite capacity atthe end ofthe table. All buckets share the same overflow bucket However, a good implementation will use a hash function that distributes the records enly among the buckets so that as few records as posible go into the overflow bucket 1.) Whatis the condition to check overflow and underflow condition in circular queue? es) ‘Ans, Ifvalue of REAR variable is greater then or equal to SIZE — 1 and value of| FRONT variable is equal to 0 then we can not insert an element into Circular Queue. This endition is known as “Overflow”. Circular Queue is empty then we cannot delete an clement from Circular Queue. ‘his condition is known as “Underflow”. 1.) What is Header Linkod list? as) Ans. A Header linked listis one more variant of inked lst. In Header linked list, ‘shave a special node present atthe beginning ofthe linked list. This special node is ‘wed to store number of nodes presont inthe linked lst. In other linked list variant if We want to know the sizeof the linked list we use raversel method. But in Header inked ist, the size of the linked list is stored in its header itself.

You might also like