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

Data Structures 1

Notes Of Data Structures For BTECH Engineering

Uploaded by

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

Data Structures 1

Notes Of Data Structures For BTECH Engineering

Uploaded by

Sandeep Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 30
es ! Pi UNIT-O1 IAS SiAOSEK | — O.veeva mani chandana pata sbsucture nT A data stucture is a special Way of Bganising | and stosing data ina comple « so that if can be used efficienty: * prway , linked Irst, stack, queue , tree, 94 ph ete, Ave | all data Atsuctures thet stores the data ino Apecial play (Well Bganised) so “tet ple Can ACCeAS and use data efficiently. | classiicalion of date Atsuchise pata structure | | Lineas Non-hinear \ . \ ! | | | | static pynamic Tree Geaph Arsay r | Linked list. stack guene | + We have two dalo prouctures + y Linear data atiuchwe 2) Non linear data Atsuchee- 1456 [NOSE Linear data Atsuctuve Gory chard ane » Elements of linear data Abwuctuve ave Accessed in a Sequential mannex , however the elements con be Stored in these data Abucluyes in Any order -(connecked one Aftes other). \ 1 4 k ked! isk, ¥ Example of lineaw data stsuctuse ave l'0 Stack, @ueue and array + * Ip lineax data Atucture all data elements are Presented at a single level. * Lineas data stsuchixes axe Eaties to {plement * Time Complexity of linear data Stuctie’ often Incseases WIth incsease in Aize. Ex- Absay Progam ~ #include int main( ) int values (53; printf (“Enter 5 integers oe fo% Cink i0j iK5y +4) t j Print £ (" Displaying integess : % fox (int ie 0; 1a Ss it) 1 Paint (* yd \n ” valug Ci7); t SeanF (* fd", SvalugliJ); Entes integers § ' 1155 INCRE ' Op £ : PV mee hetedane - 3 at o 3 pisplaying integers * ' 3 34 0 Non- Lineas data Absucture waa “ple buc buves are ste + Elements of mon-lineay data & x05 ove accessed in Non- linear Ovdes. clues ave TIES and Gjuaph * Examples of non- lineox data Ateu elements ave Present + In non-lineay clata Atsucture data at multiple levels. non-linear data structs ave difficult fe undevstand to linea data Absuchures. and implement as compared very efficient ® Non- Linear’ clato Atsucturer Uses, memory * Time complexity of Non- lineay dato boucture often semain With tneveose 0 Sige: ‘The proces, in which a function calls itaelt disectty (0) indiveclty is called secussion’s and the covses ponding function i's called o& wecursive function. » A function xf gither calls itself atisectly ov calls a function B that in turn calls. the osiinal function’ ed is. called yecussion. | ® stack is used tp Pexform Recussios: ¥* using xecuxsion algdithm 1 cextaio problems can be solved goaily. | we Examples of Auch problems ave Towers oF Honat, fone [pre ordex/ post ovder, bree travelevs ete Qum-chan\y, * Recursion ave mainly 3 types depending on Whe they a fanchon calls itself From Within itself (os) rrdle than one function call One Another routually- * Recutsiow ave of 3 types bh hkineas secursion a+ Binary secussion 3: Tail Secursion Lineas Recussion maw, ‘ If a wecussive function calling itself for one tme then ’,, wy it Ts Known as Linear Recursion". # A linear secussive function i$ a function thot only makes a single cali to itself each: hime the Function Bons. “ : x * Factovial enti igcexariple fox ‘linear recursion, Recussive algBithm mn fox factoiial “Fancton Fack(n)= tx ax 3k -- fig #n Pseudo cede, fox factorial OF an integey; fact (n) oe Poo : YF (n>= =I). veturn nx Facto ay else velusn 4; OO pseude code fox lineaw wecursion _ ——— la G5IROSSY Svem-chan lana fun (9) ie (n>o? j 1] some code | funln-1);. [teal i ff Sore code ing jkself only | J | eqr factorial Program Binasy Fecuee Recussion ; fheve ave Ewo secuxsion occuvs Wheneve® fox each non - base Case fibonace’ Aequence Binaty yecussive calls le» nth number oF Exomp Recussive algBiithe fo for fibonacer sequence fibo(ny=n-! if n>2 = frboln-") afibo(n-2) else pseudo code for oth qumber ip Abenecs sequence fibo(n) 1 if (nga) yelusn (n-1)) else yeti (Fibo(n-i)+Aiboln-a)), £gy Finding nth number PSEA ~ ~ am chandan., $F inckide & stelio.h> int fibolint); ink main ) | t ink nies Print f (Sentey 9"); Sean (* rd", 0); t= fibo(n) a prick (nth number in Sequence="d9), wsetusno; int Fibo Cintn) TF (nd=a) xeturn o-l; else yetum (Fibs (n-1) + Fibotn-2))} J opr Enter n 6 th mumbes in Sequence =F 3) Tail Recursion * IF a Becussion funchion calling itself and that vecussi< call is the least statement in the function then ‘6S known 04% Tail Recursion”. * Aftes that call recursive function. performs nothing: The function has- be proces (or) pexfoum any Opervabon at'the Lime: calling and it lees nothing at xetusning one. Recursive algBithrn tox_€eD Computation GeP (m,n) = largest num bes that dvieles both of them wpude code prude code foe 460 OF bee hump, | GED (mind Ye mnt if (ne 70) pean 9; + else \ yeturn GED (n,myn); 5 ésr Fackoyial proegion FP 2 5 (@ for lineas yecussion) # include < Stdio-h> . long int fact Cink); int main 6) d int nn} long int F, printf ( enter 0"); scanf’ (* xd » on); - $2 fack (ny; paint f (* fock = 73d" #5 sgetutn 0) long int fact Ginkn) if (n==0) -getuin 1) else aeharn (nt Fact @-1) y . ' Re ertex oS \a0 ae es numbers (Tail Recuxsion) IMSS ISB 4h include « stelio-h> Gvem: chandar int gen Lint, int); int maing) 1 Int myn) Fesult; Pring f Center mind secant (8 yd rd "yen; vesult = ged (min); Painkf (" ged= xd", wesult);, webusn 0; y int Qed Cintm, intn) i ip (myn= =o) Yeturn n; else relurn Ceeni(ny Xn); pe Enter mn ae ts a5 seasching Techniques ae erg searching (8 an operation (os) a technique thet helps finds the place of a given element 6r) value in the list Any Search is Said be suggesuccesstul (ox) Ue” succesful depending upen he thes jte-element the Is being Bearched is found x not: A Some of the Aeaching technique that 1s being Followed in data Atsuctuves, a a: 3 t + x example Sg CO ——— lassincss pun. of Lineas seasch Binasy Seare h 1 Fibqnoeei seasch ineat search yA search 1S % VES Sinple search Algaiithm: In Lineat quential seaxch i's mode pe of geasch 1 Re one by one 5 checked and 'F m is wgeluened data collection: gated ayvea 4 S$: apis ty! ove all items Every time item / a match is found pasticulax ite , otheswise the ues Hil the end of cated and ry then that Se arch contin Ik wWovks for both $ Time compkxily’ 'S o(r) - pseudo code ne n~o “procedure, linear - Search (tigt, value) © gach iker. in. the list: 2s value) if (match item gelurns the ikem location end iF End for end procedure. Hf include ink main) d int eevray [ldo], seavch C19 print | exh include ¢stdio-h> [ASS 1A0cee = : fo : Ln int Search (int avel, intny intx) G-vern- chard, i int ft; forCico, Kn; i++) i if Cary (ide ow: yelurn 1) : i bat seturo -15 5 ink matin () ? int avy { J=h4, io) 301545 int X= 30, ink = sige oF @r7)/ size of (axst0)} 9 7° print F ie hd is present at index 4d", %* search (as) n)4))3 getchar( 5 selurn o; 5 Op- ; LE" Fo is present at index 3. Ze 7 | Binary search wy Kear’ Is sr ; bh, Also known as halt- Interval A Sa a mr earch, log thie earch ov binary chi iy chop, is a earch alghiithrn ‘that feds in of a target Value. within. Aosted a: ¥ HOY. es the target value 40 the middle element of the aveay: bh works the posite # Binasy search compa® # Binary Searc for only Sostecl avvays ¢ Time complexity ( loge) ) Binary search algpiitheo 302 a ant ove, inkh tr cf implemeniohen rs) in®) In binary earch ( i if (w>=") int raid ede O-yye if (asx {mid Jeex) yeluro binary eh lars, Ly mid-ly xy else : ' xeturn binary earch lary, pnidet WHS 5 " e. 1 : 5 not found seturn -1;—? cearelad’ element sn | | J En’? include ¢ stelio«h> int binary Search (int onl, tat f, inte, t ie (x=) int mic = Lt C-a; if (avv[mid)= =%) iat x) mwoluxn mid: f if Cavs (mid ]> x) em che achein binary search Cary, tymid-UX); else . “yelurn binary geasch (ait, mit) y welurn -15 int void main (veid) q fat avs} = 1.2, 3,4110/404 5 ink n = sige of (avr) / size of (av¥foI); int X= Io; \ int vesult= binary search (ant, 0, 0-1); (result = 2-19 printf (“glement is nak preseet in avray: Print (element Is prestnt at index {A wesult); welusn 0, a 4 % - Element is present at index 3 ' ‘ = Ried Teas sorting is nothing buk arxanging the data in Ascending ox descending ovdex * The foam Soxting Come int picture, as bumansiealised the impatance of Aearching quickly. * The two main ariteries bo judge which algatithe is betters than the other ") Time taken to sext the given data Fy Memesy space vequirecl to clo so fn They a7 so many different techni : iqites gosting + Differentiated by theiv © FFicie available foy feney and space require ments voce Gy vr Following arte Some soxting techniques 1. Insertion Sovt a» Selection sort 3. Bubble sost a. Quick Sost 5 Mexge sovt 1. Insestion Soat eéhanismn Where at is. the “fosting ro 2 lime Sb a tive. Lnsestion So athe stored array is built having on ¥ The Array elements a2 _ compared! with each other sequentty and the arranged gimul taneously i> Some particular order: + The analogy. can be understood from the style e areange a duck of caxds- : * Divicle the given Avvay inbo sorted and unsorted! lists. » place the stited list a side and compore the unsdted list elements with Sorted list elenent- €47 * Tal Pe > 5 ay 6 | 1\ 3 \ rR ie by | Oy : ia | (4+ | 6 fa sy RO . psovted Qj wm rey 48510 | 'Pa'faele | x fs * Worst complexity + pa * Average Complexity to” * Best Complexity “0 Space Complexity ft * Insestion soxt pseudo code RAO Se a void inseston, sost (int, avvf Tpintn) inti, key, J} forlict; tele tat) ve i furry ot “tony key = aveCiJ : Tei-1; ; while (Fo= 0 § RawvtTIS key)? avrlS419 = ans CH; T-T- S avs (THI = key; j erample include -o aw (57> key) aw fst} = er cs} sec on vil TH1= KEY, J jak main ) t int ol I> 1s 3,411, bY vie size oF (o/ siae of (at03); printf (*Befaxe sosting")- for(int 120; ian; i++) printf (*7d", alil); insest (a7); Printf (“artes sorting"); for Cint i= 0; in; 144) Print (* yd" ati); xe hoon Oo: s ofe's = Before sosting 573,411, 6,418 Aftes Sorting V1 Bs) 648 3 ier | ao | 12 ft : oa 53) ao) lal Ie is] a | | ial | 20 | after swapping - t ! T . . | 20| t2, to | ws | a mid index 3 Selechon soxt quieehandtn | selection sort 1's nn in-place comparision Sorting AlgRittes: We has a ‘olnY)" Lime complexity which ma efficient on large lrsts and generally pre kes In fers W8lse than the similar Insertion Sovt- The Smallest clement is elected Fromm the unsfited tisk anal exchange Wish the element wt the begining. Pops — _ | io 212 | | 8 mid index! “7 y | w! wile micdl index a t T [ is! 3 | amid index 1 & Worst complexity + nY * * + 2) Avesage Complexity to Best complexity tn” Space Complexity +! Here the algBithen maintains two Sub avays ib a given Array . The subassay Which 1s abseady sorted The subamay Which is unsiited. pseuclo cocle wT (955 1AOC8S ? void Selection soxt (int av, tntn) i om ae i Ana int t, J, mi 3 for (iz0, 1<0-, i+t) i mics; swap (Qyarx {mi}, gavsti); 5 Void swap Cink# xP) Int #YP) l ink temp =# XP; XP ERYP yp =bemp; y yan Program af include « stdioh> ' void Selection (ink £3, int); void gelection(ink af3,intn) 1 ink tJ, key, mi,by for (ico; Tens itt) ; . mis tf ) for ie tr1, TanyJ44) if (atmiy >atit) mics te C fem) “beat; afi=almil) , yy almij= ty —— ASHIAC SS int mainc ) Qveneel Ande ty t int n; int ald =USr3, Hs 3 6,484; n= srge of lay / side oF ¢ato3), printf ( Before soxsting")> for Gat i20; fens f+) pantf (* xd") afi), selection (a,n); Printf (*\n after Sovting :\0")5 t ov (ink i= 0; igny 14) / | Printf (S7d", afiI); welurn 0» | | | | ,) op? Before Soxting 51s y B68 : i Aftes soxting 4 5 6 4.8 13 rere | Bubble soyt ees Bubble sovk vs a simple algdithm that vepeatedly steps thyough the list, compares Adjacent elements and swaps them, lft they axe in the Incorrect order: * They ‘pars through ‘he Ise is Yepeated until the list is Sorted. *& Moxnimum mnumbey is placed at the end. EEE shout With a'delensel Ard as sTelet > ut [aj Compare ib with WApeerk ae | | 6 | W765 H wuny sla |? | 6 19 | -9 g501 60 Suap sfa[s [6 |aiaeer * i 5| 2 | 6 la | 12/2 gcio | didn't swap sta lé [sl ja | 3 Pesull alee ihesaion | # plowst complenity sont # Averoge Complexity AY + Best Complesity +7 % Space complesity ! 4 pseudo code vd be J intr) void bubble sett (int ast ly 1 int i, OF for (iz0; 0-17 itt) For (329; yeneity det) if (003) dom (+0) susap ( & axtoy C53 yan tJ210)5 y void guap (int # XP, ink #¥P) t ink benp = #*P; > x9 ¥YP: a yp = temp; Progvact 1985 ne i ave ChaMdan.. th include ¢ stdio-hs void bubble (int Ls, int); void bubble (int aly, ttn) 1 int iJ); for (iso, fen-15 iat) i Forlico;sen-i-jdth, sy it (ots 7S aty413) teats}; ati} = ats+); . / atienj=t; i y 4 inE main( ) ' ae , Int my Ink a(9= 1-115,4/31, 6-984) Ne size of (0) / sige, of (ato): Print# (" Before Sorting’). for Cint ico; sen; itt) printf (+ rd", atin); bubble (an): Print (° after sorting Ww"): | for. Cint iso; ian} i++) gps eet ping Print (* 4d", afi) yy 3b y telurno; satler 3849 B Oro Bae 6 eso EES’ ' AT euick k sat . arelt » Like Merge Sort, Quick Sout ts clivde ard. conquiey « algtithe «Ik pick 90 element as pivok» These axe mary positions the giver array around the picked Pivot ' y Theve ave different versions Of quick sd thot peed Pivot in diffexent way 3 Always Pick fixst element a4 Pivot > always prek list elements as pivot > plsays pick wandom Element os pivot > pick Median os Pivot vialsiajel éltisia. ¥ worst complexity: n¥ # Average Complexity: n# login) * Best complerity’ byt ni (agin) Pse ude code guick sovt (ovr, Jou, high) t if Clow high) t Piz Postion (ary, fous, hegh Dy Lire Caw, lows pi-1); LE oo” fon , high) 19S5 Ao S88 partion Caw, low, hig vo. chal Pivot = a7 (high? $= low-t i for (selows, Fe highs J++) ? re (am (J) < Pivot) t l4ty swap Cari (iJ, ave6i)) j i Swap Cavsfiai] aed aval hight) Yeturn (141) Progxans — 4 include void quick (ink (7, ink, int) 3* void quick Cint af J; inkd, ioth) 1 Int ie, Joh, Peati3,b; it (22h) Cathe as dads q vs while Catiy<=pagyiceh)y i++ 5 : while ati) > p) ier; TF Ciesy i E sail, afij-atil; Olde Le ; verve a, aed te attl; | agay-atils atiys p} quick Cait d= , quick Cast, b)y 4 pit dat j ' 7 ink main( ) 4 int alpd~ Ja, 6, 814) 32147 int n = Sige oF (a) / sige of:(ato3), Print C*\n Befose sosting: \0"); fox Cink iso, ten; i++) Psintf C(* yd" ati3), quick Ca,0,0-1) 5 Print f (* \» Aftex Soxting 0") for Cink ie oy ign; i++) printf (*7%d", aliD; veturn 0; ofp > ae Before sorting 34¢9e7y 5 a) Af tes Sosting : 12346 #39 * the merge (ams, £0) 9) * mesg? sort Alga «It dlivicles inpuk array io Ho h lass Ao 8e Epvera mani cha, Like @uick Son, Mevge soxt is divide and conqyter alveAs The Merge) function is used fox meigiog fio) halves rs key process that Assume that ary fle m7 and arn fmah WI oF Aovted ond merges the two Borted sub -arvay$ into, one. See following ¢ implementation for details tmenge Sovt Carita, 8 f wo Find the middle point + divicle the array into two halves - middle m= (e447) 2 bee sovt Call mexge Sort for Fivst halt + call’ meage Sow Cow, Lim) , Cal mesge Sort fox Second halé + all mete sort (ass, mrt, ¥) Merge the tyo halves Sovtecl’ 1 stepa and 3 can Mexsge Coat, £10,8)- worst complexity « n¥ loglo) Average complexity a nx legCr) Best complexity 4 n logtny ® space complexity un 4 1 2 ae 96 TF te a i) al fl & se - * 5 ia) 4 4 2 al ‘6 = \ ho. \ rf al s | ial shee va ~\ L +> Ltjalnis | élsiq/al Pseudo code —_ = void mengesort Ciot avi (4, ints, inte) i ig (fer) tok m= i+ Ih) mesge sort Cove, 6), merae cart lors, m4, merge soxt Cars, Lien); lass no SBS x \ eum ebeind \ void merge (int ant, int L inte, intn) 2 tod; dems ke 0 while Ci 22 by dy Sehd2 it (asx i} ¢- avs (iT) Bieer) canlferL else Bl wat) = anv (r++J, % S While Ci void mexge Cink (1, int, int, int )5 void mexgesost ( int£7, int sink); vorel merge Sort Cink ast, int 2, ints) } : ve (Lew) ynt m= Gr VZ mesge sovt (ass, Zim)s bt merge 60st (A%S,m4),0) 5 CO marge sott (ars, Simi xs y ' Void merge (ink ar 3, ink §, inten, inth)q int jet deme), ko, B(20]) while ( iz= 00 85s jx=h) \ | if (ow fite eatti]) Blktt3= avlitt]; else Bert] = ort G++ds while (ic =) Blett3 = anlitt]; while Cs azh) Beery = ont) / K=O; for Ciel; reeh; f+) ans [ij= BLKHH, 4 ink main€ ) 1 int alte bb 8 4,3, 2af int n= sige or (a)/sige af (aCo3)- pint£("\n Before sesting :\n"); fos (int i20; icy itt) printf (* fd", ali), enenge sort (0,0, 9-1); pint (*\o Artes sorting: \O")? fox (iat feo; 1k) i+t) pane (8 xa" aD xeturn 0; Wir ~ efor’ sovhing 469945 al After Sosteg 1azaH 6489 L ’~ 19s 5 IN0soe os Befowe * a chars set bonacci search : Ra RN an sige 0 an Gives a soxted Avvay act] of $i ™ be Ae arch Refusn index oF % Fit clement X te Kearched in ite elusn index © ii Elemen iS Pre. in aye se yeluyn -! is present in avsay Else ¥ GF npul | AWE] 2 9.9/314110,404 7% =10 - output 1 3 Element x is present ak index 3 npuk fave 3229, 314/10, 404 ,X°" output} -1 Element x is not psesect Fibonacci seaych iS a compasision - based technique that uses Fibonacci numbers’ to, seach an elernent in a sosted awry. 1s W3ks fox sited arrays ‘ a+ A Divide and Conquer algdittim 3: Hos “bog n" time comnplexity + Fibonacci seach divide, given ayray, io uneqpl posls: * Binary search uses division ‘operated fo divide vary? Fibonacci feaych doesnt UKE, bub UMA + eal divisio f Operator may be costy on Rome cpus + Fibonacci feavch examineys relatively clasey elmo" in Aubseq, uent steps So hlhen input Array is bi she i cant iE in cpu cache oF even in RA Fibond Rearch is upeful ve See IND = BMAD a Ef id) progya> INGSIAOSES tringlude Veen-chandare ot include < chyperh> en iat Fibo Cint 9) ip (n<=2) sebuxa(0-1) 7 else ease (fibo(n-!)+ Fibo (@-2)); gerne ‘ int min (ink, it 7) i xehuin (men 27:0); 5 inh Fibosedach (int aut Ling x, into) ; : Fibo mzo ,opf =! 1; while (fibe(indeny [#21 0-0 Gt at 3-a7 4-3 5-6 6-8 4°13 m=4 arr {J =210, 22/30, 44)5%6, 58, 60,100,110, 1304 */ Mem+); while (Fibo¢m)>1) 2 fe min (off + Fibo (oo-9),n-1)- [¥ Search Inder is f ¥ Printt ("In ievid mesvd off- Ld" in ptty ~ AP (x > ani) i m=m-), OFFat, , 5 else l9Ssrao ces ia ba utd cn tf (xzant'd) ay m chandar mem-t else yeluwn fy 4 e rt / IF Cfibo Gm -1 &Yy ares (off +1 Je =X) |+ oe element + vehuro OFF +1 Beluim -) ink main¢) t lok AL} 210,22,35, £0, 45,50) 30, BB 185) 10/104 X= 35,045 N= Size of (ansy/ size OF (avsto3)} f= Fibo seaych (are, X19); sit (#1 = -1) Printf (* Found at yd ",f): else Print# (* Not Found"): te4 mas opp __y + mest Off=4 i-q ™M==6 Off= 4 mrt OFF = 4 Found at ¢

You might also like