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

Introduction

DSA

Uploaded by

ssmukherjee2013
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
24 views

Introduction

DSA

Uploaded by

ssmukherjee2013
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 11
notation, omega 1 are used because However the effic related by a const Complexity: The complexity. The time complex the algorithm. The space comple completing the ex tive attributes of a vari jive or quantita a " walitative oF 4 ble ), refers to Gua measurements and can be the basis a data are the Fest ‘sata (plural of “da i ally. riables. Typically. Care ter of variables. . : ve i 4 fata. Earl Jnnges or observations O vareription of other data Earlier term fo gi iteradata is @ data, containing ancillary data. many different ways. The logical or ma Data structure Malled data structure. adel ofa parity linear and non-linear. + Classification: De Sere said to be linear, if its element forms a apes The data structure is sa Fits el i or Fines ta structure: In nonlinear date struct data elements are not organi oral fasion. A data item in amonfinear data Sag could be ached se tn : ne a fest a speil relationship among them ant a I the data item traversed in a single run. . " 4. Mesee ations can be performed on data structure, List of some equ operations are given below: 1. Traversing: sometimes al process the data. 2, Searching: finding the location of record to be processed. 3, Inserting: adding a new record to the structure emoving the record from the structure. 5. Sorting; arranging the record in some logical order. 6. Merging: combining two different sets of records to form a final set of records: * Abstract data type (ADT): Abstract Data Types are a set of data values and 3 operations that are precisely independent of any particular implementation. The signifies that the data type will only set the rule of it's usage but how it will be use” ‘on the implementation. For example stacks and queues are called abstract dala stack data type defines two abstract methods PUSH and POP. ‘+ The basic properties of an algorithm are: : Input: Each algorithm is supplied with a ze sa Ouiputs Each algoriim must produce alleastone eat Definiteness: Each instuction must bean gon Finiteness: The algorithm poe be clear and unambiguous. terminate after a finite numbet of steps within fil Data may be organized in Jar organization of datas a structure can be classifi nuit arr is 2000. The loc a) 2820 * Answer: (b) In C language, m a) integer point: ¢) null pointer Answer: (c) nly Jso called as visiting, means accessing the required reco : 3. Which of the foll a) O(n) Answer: (b) 4. Four algo.s do” Values of n? oe a) O(n’) Answer: (d) §-InC language, an a) Col cian om ‘majo 8 Na Vhich of the fork Effectiveness: Each instructi; © Analysis ofan alge tO8 be suficiently basic and also be Feasible: sven) Storape) necessary 0 exeere © determine the amount of resources ( See lx. Usually the ficiency (Mos algorithms are designed to work wth ings MOHEL- Which not eee ining time of i z a compteaiyy net (© the number of step cine e ae e Anse) ae st a plexity) or oe ‘NSWer, ©) Scanned with CamScanner DATA STRUCTURE & ALGORITHM notation, omega nota id theta notation Me used because different implemen Are used for this. Usually asymptotic estimates ations of the same al complexity. 1e complexity and space ‘The time complexity of an the algorithm. ‘The space complexity of an algorithm is the amount completing the execution of the algorithm, Multiple Choice Type Questions {.Each element of an array arr[20][50] requires 4 bytes of storage. Base address of atris 2000, The location of arr{10][10] when the array is stored as column major is” 2) 2820 b) 2840, ¢) 4048, ) 4840 [WBUT 2008] Answer: (b) ‘mount of time the computer requires to execute t of memory space the computer requires, 2.InC language, malloc( ) returns ) [wBUT 2009} a) integer pointer bystructure pointer «¢) null pointer 4) void pointer Answer: (c) 3.Which of the following is the best time for an algorithm? [WBUT 2010) a) O(n) b) O(log, n) 6) 0(2") 4) O(log. n) Answer: (b) algo, should execute the slowest for large 4 Four algo.s do'the same task. WI values at? [WBUT 2010) 4) 0(0°) by O(n) ©) O(loB: 0) 4} 0(2") Answer: (4) ; tation? qweut 2011] SInC language, arrays are stored in which fepreeseiet ont a) None of these 2)Column major b) Row major swer: (b) slowest for large values of : [WBUT 2012] i the iqiich of the following algorithm should execute a) None of these a 7 c) Ollog2N) ae b) O(N’) [weuT 2013} Igorithm)? a rie d) None of these Which i lysis is better computing time (in analvsl® 7) 4 O(n a oe “ b) O(2n) DSA-3 Scanned with CamScanner x opULAR PUBLICAT for desired records jn. | we can search s in'g) where We - ture iW 8, A dynamic data strut by binary search tree nny presented ray 3 Jum. mantels _ cau em rows and ocean tke wrjements. This m xn Answer: (°) JAmatrix, that is filled wi 2] th element of a 3, i 7 address of [3 4 Ta 3x ‘matrix. 9. For Column Major what is the that the ‘Base Address is 2000". jwauy en f there is a sparse iv , : (ntaine integer oben 1S 6) 2016 4) 2018 FF tore this matrix, then the a) 2010 Now. a sparse matrix can Answer shouldbe 2020 Inthis way we can store ¢ ns access the (i, jth entry of a (mx) (weur: i ing expressio 40, Which of the following © stored in column major order? ae, act, ymegonel e)mx(n- Answer: (b) jing is non-linear data structure? 414. Which of the following is non-linear u a) Stacks b) List ¢) Strings Answer: (4) Let us consider a matrix N Here the number of non-z The array A [0...t, 1...3] 3 7 1 Short Answer Type Questions Alo} asc] ot 41. Let the size of the elements stored iri an 8 x 3 matrix be 4 bytes each. TU ajo] 2 address of the matrix is 3500, then find the address of A [4, 2] for bothret tggg ais) 3 column major cases. (weUT 200 AL] What is sparse matrix? Bass oR, s ‘What are sparse matrices? How such a matrix is represented in memory” 4 2. the types of sparse matrices? Show that the function Answer: 1" Part: a 4 fort 30 In row Eon the address will be S= fe Therefore Y= LO*C)* n+ Guy) He has the co Lee (84.2))= 35004 (4 2, 2,6 not rd =) -1)*4= * 500 + 4 sao ” ea) ‘ene the address will be Therefore . Demons 122 (A) = 3509 + 500 + 4. ePresentativ es. ‘fine Big O notatio Scanned with CamScanner is represented in memory as 2D aay, lke A [i ‘ 7 column. J}, where i is a row and j isa rows and n coh yrahere are m FOX lumns, then total elements i 1 : : cadets Thism xn elements requires m enects ina marx or sie ofa mati is ‘matrix, that is filled with mostly zeroe: rage. jl ose max 'Y Zeroes (more than 2/3 elements aré zero), is called as a ow: ite a sparse matrix of order m x and if we use a 2D array of order m Xt sore this matrix, then there is basically wastage of large amount of memory. Z Nona sparse matrix can be stored asa list of three tuph Fr : les tebe way we ean store only non-zero clementgs ese Ce vale 0 00 Let us consider a matrix M(5%6) Here the number of non-zero elements t= 5. ] can store all the non zero elements as given below: 3 5 1 The element A (0, 1] and A (0, 2] contain the number of 2 rows and columns of the matrix. A[0, 3] contains total 3 number of non-zero items. 7 30 ‘Show that the function /(m) defined by: [WBUT 2007, 2010, 2016, 2018) f(=1 : fin) (n-Deh forma! has the complexity 0 (og ")- ine Big 0, 0,6 notations. Explain the vera ids De conceptual differences among these IWBUT 2007] mine entatives. JBUT 2010, 201: ‘fine Big O notation. mw at Scanned with CamScanner ee POPULAR PUBLICA B= be fu Answer: gn and gn) be fi y" Part ej only if en) = Oe @: fan) and ef) be fis Lely if an) = Off 3, Derive values relat Sort algorithm. Also, c Vit 24103 +. J “These types of numbers are called Harmon numbers. fio’ ; We can evaluate this type of series just by integrating I/x from % tont % : her egating, we get the result a In(n + %4) In % =Inn-0.7 Hence, we can write the complexity as O(log n)- |rite an algorithm for technique and find its J Answer: rithm for bubbk Big O notation: ‘The Big Oh (the "O" stands for “order of") notation is used to classify fir asymptotic growth function and hence finding the time complexity of an There are two types of complexities of an algorithm, time complexity complexity. The time complexity of an algorithm is the amount of time the omy Swap L requires to execute the algorithm. The space complexity of an algorithm isthe End if memory the computer needs to run to complete the execution of the awl hen | algorithms are compared based on their performances. The performance S2=Mbncivies terms of time complexity & space complexity. Based on the nature of th} complexity can be of three different types: best ba I rt : best case, and The fferent computing functions aremeasuredass For j = ist TE Listli n,m 1. logan, nlog on. 2°. ‘The rate of growth ofall these functions is shown below= Scanned with CamScanner DATA STRUCTURE & ALGORITHM ny and g(n) be functions, where mn is a positive : ea an "ere 1 is a positive integer. We write fin) = 2(g(n)) if ) and g(r) be functions, where 1 is a positive integer. We write An) = O(g(n) if O(ftm)). and gn) = Gin), [WBUT 2007) jwite an algorithm for sorting a list numbers in ascending order using bubble sort jechnique and find its time complexity. [WBUT 2017) JAnswer? ie algorithm for bubble sort is given as follows: frocedure: BubbleSort (List[]) Inputs: List{] - A-list of numbers i, j - integers 0-to List.Size-1 = i+l1 to List.Size-1 TE List[i] > List(3], Then Swap List [i] and List(j] End Tf Next j Next i alysis: . he size of the sorting problem is related to the size N of the list. AsV increases, we pec the execution time to increase as well oh he imermost instruction is to swap two list elements. Regardless of how long the list is, is always takes the same amount of time, and so the swap instructio ow oa “ect to N. Surrounding that instruction is an if statement, which aie at f° 0° des not in the worst case, it wll exeute body. Again, the if statement is executed as many times as the inner ey ee aiae Wes as many times as the outer loop iterates. During the UN, TT ee and 50 : ; tration (i Sloop executes N— | times, during the second it 3 = O(N? -N). a )) =o" te | a ee 00? ; GnmberoFloons —ume-Por rst ente. 1 ompleity is O(N2) inthe average €28® ay bi ie" case would be ifthe list were already SOMES: time ig in O(N2).. ul © comparisons as it is but ae a ‘erminate the program checking if ei ii ich past d max, (N=I Sora ae of exchanges yd eure oon at a ma anges, DSA-7 o( Sw- =x LI Scanned with CamScanner TION : ULAR PUBLICA! popuLan pusLiCATIONS create equired in that single pass ate te iforen compass req oes order of O(N)- The main differ is linear data structure? fers to an array off P 4, What is fhe fact that multidit Answer: cecad bene ene form a sequence ora lin fumber of elements ‘a data structure is sol smb ly present Examples: : + Arrays 9, Do a comparison a + Linked Lists + Stacks, Queues | . ‘he Operon that can be done on Tinear structures are structure . rsal: Travel through the data sl : ee ee through the data structure for a given element . ‘insertion: ‘Adding new elements to the data structure + Deletion: Removing an ‘element from the data structure + Sorting: Arranging the elements in some type of order + Merging: Combining two similar data structures into one. Answer? Data type consists of t or character data type operations that can be for addition, subtract pesform these arithme part of the integer data JA data type can be co Jand its implementation fanother for, e.g., effic program). Thus, spea considering it irrelevan A data structure is an a An exaniple of several binary trees, and hash t an be implemented as 5. Prove that, O(f{x)) + O(g(x)) = 0 (max(f{x),51%)) 4 Answer: Ke Suppose q(x) is in O({x) + g(x) ) then q(x) is in OCmax(f(x), g(x)) because greatest of f(x) and g(x) is greater than or equal to the sum. More precisel (x) <= e(f(x) + g(x) <= 2e(max(f{x), a(x). . Next, suppose q(x) is in O(max({{x). g(x)) then q(x) is in O(fKx) + g(¥)) greatest of f(x) and g(x) is less than or equal the sum of the two (assut functions are positive valued). In formulas: 2 (%) <= e max (F(x),2(8),h(X)) <= ¢ (fox) + B(x). Hence proved. 0. What are the differ nswer: Pata structure can be cl a data structure: uence or linear list 1) Lage ete the elem megat Felationship a) Treory locations. : Telationship | 6. What is Structures’ o” Abstract Data Type? What do you mean by # P Answer: An abs ‘ ipleariciiercar (ADT) is an object with a generic description MO the fintions to Baresi ot & Paticular collection of-data only the Stull Performed on the data is defined but the impl defined, then such a collection of is called Abstract data type- collecti a : ion of data is calle time and only requi mory allocation for the data structure take® ‘quired : endo am i Eps Link its, Stacks, Queues Tre allocated. Scanned with CamScanner ATA STRUCTURE & ALGORITHM o the difference between aft} and +a t [WBUT 2012) difference between multidimen y of parti fre ct th ensional arrays sio1 : sonal arrays (aI) and arrays of pointer (**8) ‘ays (a pointer to pointers to that datatatype) a g : eer of elements allocated for fae Sal data structures, with the same ily present nan array of pointers, N'4 Mimension. This constraint is, not t cess ison am 1.00 comparison among Data Type, Abstract Data Type and Data structure. (BUT 2013) answer? w 1 pa ype consists of the values it represents and the operations defined upon it.. Integer ce character data types are found in nearly all computers, and théy have well-defined pertions that can be done with them. For example, the integer data type has operations x aidtion, subtraction, multiplication, and division. The computer knows how to jerform these arithmetic operations with any two integers because these operations are ratof the integer data type. 4 data type can be considered abstract when it is defined in terms of operations on it, 1 its implementation is hidden (so that we can always replace one implementation with efficiency reasons, and this will not interfere with anything inthe wgrm). Thus, speaking about such a type, we leave its implementation aside . nsdering it irrelevant fo the topic, unless we directly discuss the implementation. | data structure is an arrangement of data in a computer’s memory or even disk storage. 0 examiple of several common data structures ‘are arrays, linked lists, queues, stacks. binary trees, and hash tables. Data Structure is an implementation of ADT. Many ADT anbe implemented as the same Data Structure. 0.0 i linear and non-linear data structures? at are the differences between lin Toor, 2014) past i near and non-linear. ia dat See aa anc He said to be linear, if its element forms a uence or linear list, There are two basic ways of representing such structure in enor. Here the cleants are traversed sequentially stating from the DegINyINg, ) Linear relationship between data elements 'S represented by means of sequential Memory locations. Ex: Arrays. ) Linear relationship between data el links, ed by ineans of pointers and resent the data having a hierarchical tie not traversed sequentially, rather case of the tree, we have to rt subtree, but not the elements in. For example, in i tree oF rig Fom the root but we have to traverse either left su ‘Sephs and Trees, DSA-9 Scanned with CamScanner cc istics Of algorithm? ton stated(defined). iuniquely defined and only q Mead s of eac oa emax ¢ f=" : receding Steps: 0 ier It 7 Sesrith stops after a finite number Of instructions ae a \ 2 + Fintenes gorithm receives PUL IGF rence proved. Input - the algorith duces output. = rithm pro’ . + Outpt the ree rith applies 1 a set of inputs. I © Generality vame ise : sa intatized a8 int 2 [SY(7I: B2S0 adireg «ff, write short note on Ab 12.2) pp ee mar frm and CMA Maori answer: Refer 0 Quest the location o! b) Define Sparse Matrix. Answer: : ; ‘} assume thatthe size ofeach element is 4 bytes. In row major order the address will be . . Lac (A(ij)) = Lo * (G1) # 2+ G-I) *e viependent description of t ‘Therefore, Pseudo-code is an artifici Loc (A(2.4)) = 4000 + ((2- 1) * 7+ (4 = 1) * 4= 4000 + (7 +3) 14 gorithms. It is a "text-bas 1000 + 40= 4040 Bana informal high-level des tructural conventions of a ther than machine ig uman understanding of th ode and subroutines. 2, Define pseudo-code. xamples: _If student's grade Print "passed" ise rint "failea* region of unknown data type. 3 The (char*) or (int*), is an explicit type conversion, converting returned by malloc from a pointer to anything, to a pointer to char of is unnecessary in C, since it is done implicitly, and it is recommendé this, since it can hide some errors, Set total to zero iy eroce counter to Srade counter i REut the next grade . dd the 1 14, 1f T(n)= 2 3 E © grade into th (n)=4, +a,2+0,x" 44,3" +...44,x", then prove T(n) =0() pct the class avera ty pI i ge Answer: At the class avera To prove that f{n) = 6 such tha O Signy ee we have to find cl, €2 > 0 and no Ba Marize cota e tei f(a) © the first grade ag the user has no} a=(g-2 th: h : (: FD) % omt®, 9¥ade into tl "© to the grade ¢ DSA-10 Scanned with CamScanner ICTURE & ALGORITHM |, write short note on Abstract Data Type. b [WBUT 2012, 2015] answer: Refer to Question No. 6 of Short Answer Type Questions. 1. Define pseudo-code. [MODEL QUESTION] Ansver: tual purpose of using pseudo-code is that it is easier for humans to understand than sonventional programming language code, and that it is an efficient and environment- independent description of the key principles of an algorithm. Pewdo-code is an arti and informal language that helps programmers develop gorithms. It is a "text-based" detail (algorithmic) design tool.Pseudo-code is a compact informal high-level description of a computer programming algorithm that uses the ‘rural conventions of a programming language, but is intended for human reading than machine reading. Pseudo-code typically omits details that are not essential for man understanding of the algorithm, such as variable declarations, system-specitic ode and subroutines. samples: If student's grade is greater than or equal to 80 int "passed" int “failed Set total to zero ft grade counter to one ae File grade counter is less than or equal tot yait,the next grade Mi the grade into the total = . ft the class average to the total divided PY Fo in the class average. jdtitiatize coeat to: zer° Ralize:councer. to zero hie the first grade sentinel Bits the cane bas moe ac ver Stee 8 hy MS grade into the running Me to the grade counter psa-il Scanned with CamScanner ggibly the sentinel) input the nex! Sere if the counter. ta ot ioral divided by the. counter set the ave brint the average se i . eine ‘no grades were entered @ Chapter 4, initialize passes tO zero Ch: p' 5 - stalize failures to Zero Moe deat initialize fai. ie ee initialize student to © ete sie A i unter is boar while student counter 35 * Seapca ‘The POP operat input the next exal if the student passed add one to passes else add one to failures ‘A STACK is cal «A sstack may be | element of the sta linked stack. The add one to student counter typede print the number of passes { print the number of failures ine if eight or more students passed en print "raise tuition" } Ista Astack + Various types of operations (opera Infix notatio Prefix notati . Postfix nota + Conversion fron corresponding po: > Fully parenth > Move all ope * Delete all par The priorities of ¢ Priority Queue: associated with it SPeak of one item Which is the highe qheue in any, ar their priorities st + puttity are proces: 'e-queue: De-que Tom either end of Dsa-12 Scanned with CamScanner

You might also like