0% found this document useful (0 votes)
85 views76 pages

DS Unit V Handwritten Notes

Uploaded by

chennipadma
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)
85 views76 pages

DS Unit V Handwritten Notes

Uploaded by

chennipadma
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/ 76
Stack AST EE Ont 4 | 2 o> | Slaw 8 a lineay data grrucpuowe PD wuch | the otements ane added or romoued ond ot ono 2rd, calted Lop of the Stack. # syack folie The prind Piwst OULD. The element that ts Pnsertrel (age Po Poy Stace ig He Piet one to be rerpvwed prom Fur Saen ea a ee oP | a gyack of Bootes y: \ Cr | - a Sack of cwint ” { - & clack of PLAbes Ba fe tOP OpBaHtons ff ) D puth cy) —Prawrting an eloment Sato pe eee is 2 fake CD pop = ventaving an oternont from the top OF to stack . exeptfon cwonchitt Or wu a Overpeor v i . attemprng to inset imo @ Full Gace wy cncexfou7 ~ attempting jo caleba from an entphy sfack . Emptomantation of sack sjack con be Preplarrented In fe ways. O aay Prepementatico Gd L9uA Ur Frepereatation | eat fnpturantatton Lhseation v p Saree top sole ae scsi [to] Fe tp sofas | yetep cco[e | ca) amply. NOW ties for Ph ga is pope! To push anctemort % onto fue sacs COP & mnoemonbs and see SCERJ =a; Pro tune po inser vad push Cdype x1 qype cI TEC bop = = anraycize -12 © oyncrt ” gace is ovsefcnw "27 popes? por cs) popes? per wo a seal Sil "eo Je Tep oF a) estop go delet an otemoxt srtop) & verernad and top poratss B ctoomorted . — ; @ DO push 305) push (401s) Rouwtna to _obelets sci) void pop C kype | t ip( top = =-19 | q pwr spacn & cnctexfeow "5 | % ote | £ tN X= SCtopl 5 top ~—; 3 P Howl Ie voprelentatio of Secs | duclratin of anode & sien nod Shuck mole | z Lemont > jos | +Yype . we | ———- Pe = tl; 4 3 ee 0% Hypecett Shrnck n0ole ms jack ; | Entakteo | : ’ otomort | fh opoation & pexfornad seeing an at Ho top ob Ts ee 4 I push (ws) top top _ i PE" — pe | amply stack | | puro 'B) whee aly igetle, | top _ era, pep Te aHe1Z | ya se NSO, 7 i puth C type 21 Stack » z gyruce tony; coup = malioc CSI TFC kenup } = = nolL) i ‘op Cgruece noel )) 7 as) temp > ebemont = 4 E2np PNK = 8 > Noy 5 Snort = ‘tony; se gyack is oussfmw't) 504 2 parotiso fun top of fue Use B pastored a ty aA P popts) Tetum cunctanteons OT - - G Sank a a og nee = NULL Cnr] | para Goals bez s Tey mp (000 2000 before Aoletion ates ctolstler pousine +0 qutete | chute nnolo #tonp ; | df (3-5 nee = = ULL) L erort.’ sfaok & coniatiow Iz | euse z bop 2 Sonat, Ig ee a Array implementation of stack #include #include #define size 10 int top=-1; int x,top; int s[size]; void push(); void pop(); void display(); main( { int choice; clrser(); while(1) { printf(’\n 1push\n 2,pop\n 3.display \n 4.exit\n"); printf("Enter your choice:\n"); scanf("%d" &choice); switch(choice) { case 1: push(); break; case 2: popQ; break; case 3: display0; break; case 4: exit(0); default: printf("\nWrong entry ! try again"); void push() { printf("\nStack is overflow"); } else { printf("\nEnter the element:\, scanf("%d",&x); topt+; s{top]=x; display(; } void pop() { if(top==-1) { printf(’\nstack is underflow"); else printf(’\nDeleted item is: %a",s[top]); top--; } display(; } void display() { int i; if(top: -1) printf(’\nstack is empty"); else { printf(" \nContent of stack is:\n"); for(i=top;i>=0;i--) { printf(" %d ",s[i}); } } 3 Linked list implementation of stack #include #include struct node { int element; struct node *next; }*top=NULL; typedef struct node *stack; void push0; void pop(); void display(); main() { int choice; clrscrQ; printf(’\tMenu \n 1.Push \n 2.Pop \n 3.Display \n4.Exit \n"); while(1) { printf("\nEnter your choice\n"); scanf("%d",&choice); switch(choice) { case 1: push(; break; case 2: popQ; break; case 3: display(); break; case 4: exit(0); default: printf("Invalid choice\n"); void push() { int x; struct node *temp; printf("Enter the item\n"); scanf("%d", &x); truct node*)malloc(sizeof(struct node)); temp->element=x; temp->next=top; top=temp; ii display(); 3 void pop() { struct node *temp; if(top==NULL) printf("Stack is Underflow \n"); else { temp=top; printf('The element deleted is %d ",temp->element); free(temp); top=top->next; } display(; 3 void display() 1 struct node *s; if(top==NULL) printf("Stack is empty\n"); else { s=top; printf("The elements of the stack are : while(s!=NULL) printf(' %d ",s->element); s=s->next; } } } Que & an APT and a Linean cata Shuck Ph WwHCh tue clement asr asvanged $7 saquosesal ovde, 7 The elements are inserted at tue Kean’ end and tot Pom tuo “front” ond. x Quucet, ate bated on FIPS (rei) £0 Pode out) | peinuple , frat meant tut adomwat that b Pneestet Pirsr | | fy tun QLeguer OB alo tus first one queue - to be Fenmoved Len jus} | dequne O <_f Our Je— enaweue i t Front fon Qhamplo : Aus of people In HCmok coceates o, ons henge = Imbertng an etemom ito 20% end ui} olequauec) Henwying an element from front ed | exception conalEons _ |) cuwrfiow e? - attempting Je Incere frto a fu quer | la undexfiow B — abtenphig yo chelols Froman | | fmpuernancalicn _ | Gy Array sriptanoatation | — | Cid Hod Udt amapiemond tier - | oo | emanate ' mot ouph stieo for Pnseaticr cog es | an ae | cor frowns =) t t ampig Quis ee engpume C10, A) OnQuTe Chor 0) — erguentc 30 Q) oes cerry Lejel ] (whole J a 1 Ff Ouesdewen | Fr for fox | JO IMALE an closest “ye “to toe Que QV, | | Cray =x; ‘Ths x0ax porter & inowmented by L ard 20t acred =) Rousing 40 jre.out void onqueus ( type rx) HP cy exsor" Ouue U ouoxfrow ") > | A | RAK +E D e~ QCraaxy= x; | Deretien | To clolele an element AL frouel & retwerncd card Tha front pothter & inwamentd by 4. Case ds opty Onn Qloment fn tue Ouse U when we delete that elomot uur must} be et to be an empl Quas cok 2: mone than one Olemwat fn tur Qiuaree belereotobler logue CY) ofty [2 [ao [24 s. dutetbe pop ERT | simply. Incamont tus frone Pornlen by 4 Routine to dnl vord aaquoue Ciype Yer ca Cree = 2-1) ener uous und esfow “Ds eLse 1 eq chou : | it front = =y205) [[ Case) ~ only one elomen q Prout <0: Intus Qua 3 YOY = -75 olge (€ case 2 ~ moved nar OM 2 Pronk = Font +1 Quo & Liwed Up emplermontertion with tinued Up a (usc can be preated on tte ceauone Of nootes with Tue Potow ke fer caclasatio ol a nate annals Shute root [examen [re zt dpe ehament + Siete roca. * nove 7 4 * Pronk = wore, * reas snuw; typeof Sri rool F# Aratee 5 Crs ectioo erauiu operates & performed ah THe Xeas ond case 4 Preestion —Itfo_an tue of BS (CEA eee, reap] 4 ca 2. Snsestion info a non LPI QUABCe voepars anneal, arauss (200 0) pene afi WOE ad Todt al pate T A | | Rounne fo insane Void angie C Hype xX, Qunw @) Shuth Koote * temp 5 tomp = malloc C sizeOf Cspuet nrocted), TP (wean = = wolt) IL casey - t EMP -y otomoml = x; | benp > nase = Noe; from = tanp; 3 Yea =teny; cue { fomp > clomont = x, | Cop > ndek = NULE; Deut = Eeatp ; 3 Fed = tenyp ; UWcame 3 Hotettor pequn opeattes & paorned at te frone of teu (ese case 4: ony) Om otemert in tee Ouse | Routine fo ctolote wend doqseue C Aus OF © onuee noole * Gp 5 if C front = = nol 2 graor( " Quate & cunctentenin "D> % ebro 7 bemp = front > 1H CAont ==veea? (| case? £ front =NULL; Yeav =nue; 3 Preectamp): eur (Lease 2 eee = Pronk 7 neee; 3 Pree Chomp) ; | 5 SGM m® Boych proceming in 9 A TO fplument Priority QuUsuH i 0 mamel coves ng, user queuing Theoy % Pmulation w» coniputy mekwore we Naniag neerougp: > van) Hou. sty H Seu TG Cegushy ON A Ane ae renee 3 cpu schucteling , olusle Achaliuley . r[o duper win veut Gfe, call canter phone poms will UE | qusutt, fo hod peop caltieg pro in an OrLOt , eri! OW Geswite vepreerfatiut B free - | | @ | Implementation of Queue using array #include #include H#define size 10 int rear=-1,front=0; int qlsize],x,i; void enqueue(; void dequeue(; void display(; main { int choice; clrser(; while(1) { printf(".Enqueue \n 2.Dequeue \n 3.Display \n 4.Exit \n"); printf('Enter your choice : "); seanf("%d",&choice); switch(choice) t case 1: enqueue(; break; case 2: dequeue(; break; case 3: display; break; case 4: exit(0); default: printf("Wrong choice \n"); } } } void enqueue() if(rear==size-1) printf(’Queue Overflow \n"); else { printf(‘Inset the element in queue : "); scanf("%d",&x); reart+; alrear]=x; 3 Nees void dequeue() { if(tear==-1) printf(Queue Underflow"); else if(front==rear) printf('Element deleted from queue is %d ",qlfront]); real print{("Element deleted from queue is %d ",q[front]); front=front+1; } display0; } void display() { if(rear==-1) printf(’Queue is empty "); else { printf("Queue is: "); for(i=front;i<=rear;i++) { printf(" %d",q[i]); } printf("\n"); Syearq, {(,u\ e0t0yo pyreauy, yruErd “ameyop (Qaxe 2p esvo syeorq ‘keydstp 1g 0sv0 spearq {Qenenbap 2G ovo syeerq sQenenbue 11 e880 } (coroya)yoqtms FT PEAT {(@ar0yo9',P%,)FuBOS {Qu a010yp Mos roTUGUY,)pyUtAd GUI O\, Aepdsrq’gu\ onenbeq’zu\ onenbug’ TH ANGINY \,)yraEd 3 (eras feoroyp yut } Qurew x Ur sQAeydstp proa Qanenbep pro sQanenbue proa fonenb,, epou yonxys yopeday STINN=2802,TINN=109,{ ‘qxou,, apou yonzys queureye yur a epnpoury opnpoutye UISH SHSHH Jo UOPEHTOMTOTAMT void enqueue() t struct node *temp; printf("Enter the element\n"); scanf("%d",&x); if(rear==NULL) { temp->element=x; temp->next=NULL; front=temp; rear=temp; } else i temp->element=x; temp->next=NULI rear->next=temp; rear=temp; 3 ee void dequeue() { struct node *temp; if(front==NULL) printf("Queue is Underflow\n"); else { temp=front; L_ temp=(struct node*)malloc(sizeof(struct node)); printf(’The element deleted %d ",front->element); if(front==rear) { front=NULL; rear=NULL; free(temp); } else { front=front->next; free(temp); 3 } display0; 3 void display() { struct node *p; if(front==NULL) printf("Queue is empty\n"); else { p=front; printf("The elements of the queue are :"); while(p!=NULL) ; anor Here + by eet (tesh jap alr The fash tabu hata spre cet | et come frxsd Size ordre $1 eed" [raatg | yoshi & a ceORNaW used Tor perfor mt | pcotidrs , ctolrtinat ard aaach epexattes Po compan | gh. Hypa 8} Hehe | gy stone nay toa fied | arn Fanciien reaps Seach wey ous pneatton | C) Dy ranue Had hory , | Jen. | ek yabe can gan te handle. nome | Hash _tedble. a an array seoath & posfownad en come pare * each Koy & mapped — Pnko ome nanbor fn Ft ange 0 te fabustze-) and piawod pr sua Appropes at | ceu que rrappirg & calted os ‘hod, funte! © yesh Functivo » . A prep. hath Punction & Guana, fash CKoy ) = ey. riod FR e g. Hash (10 = te wl (Oe . fo ft Kay volun tS a pad en melodie ob 5. 2% ae 4 Fup — (a S720 =L0 Poulint for shape Hath Functior Pre Hobh Coonst char * kay , fre jabuesive) 2 Prt — hashwal zo, wiik CFL fe oD . / | | | fathual, . * [3 vate Cashel qe aecsres): some of tes mattis of Aashy Juncyous ore, W mid square mottred CY pseyalo rondom nierdberr genvater mottud | ©) nadix tron for malin ® aigre or character attraction motuod colurt Leo | re & possvbe that fr hash Funclies gematu h tuo hefperort voles + gat fash aye Fer oe tte nt oe tered | at fun soma poottiin pn tue hash fable The | cated | | | | | | | — auadsoe Proery | erated Yothesy - poube Hadhuy | luy Extondtble Hal hing Separads Chaining nd. inth > call ad gpen edelsouchy | eras “eames chews B fo Koop a (ue of ae efamonts | h game valud- 4 pop tey ad & actoted each xacsrd Locotiro. Ren FF . of when an ourxtiows occurs. this porter B set to Pernt fo cvmfiow buceet OKI a (frikad We. x cach (nyad Ut coatrs all fur elemonts. Winse toy hath jo game frat Hene fur fab can new ouerf ow - Orls By, los 4, 64 88136 Ths. separate chasneng can be vepeesental bY posh = x nul fehg,,; CO posh (XI = tv 7-00 & postowm ¢.20uCh ar UR hath Fur cion +0 capbeamrnt. wich we @ fo grauenke ¢ than A Sauch pus appropri alo (ur To Jab gatte Toca enutk = Hechtbe * yesteahess | | yg CHIL TH appyopricte (Ut war otomont & alswody fr place. reg [Yeus Palate. i | pod. * post tee? poo KE, | | Dropotization oupenr For separate chasing Hashtable . Intielizepable Cut fopasrer) Yesh ab Ys Pre Po i Cpebudiee < mop fablegi ze) a ‘oyver C" gable tiza B F00 small "7. PUAN NULL, : 3 (CAUocate fob . CRA RRS + Hs mole Csize (Shree Hasneeey) ; e if CyH=seuw oc ar WP - 4 T pasalosonr Crouk of Space 3: © Fs jabtatize =noxeprene Cfablesieed: YW duncats ora Y tuts : 1 Yorrhebits = malloc CsizeOp Clue) eH fablsi2D, 13h CH Thelesis = =~ ULL) . a Fataleneuor ("oul of Apaw > oo for CE=0% CCH EADS) *2 7 cH? 3 yarn We Coo = malloc C8i zeOf- Con ee rota y)., oo Tt CH Thee laps cigs nol a Fatalenor C " pub Of Space "): ‘ ; 20 > The ts COT Dneet anolls, ren 7 | tenes 7 trough [o auoats ao heth toble spreckwu. ot spare & avallobl. tron YH us poPrt fo & spreceure | contatury an piteger asd porter to a lie | Lene UW sets tur jabluitze to a prfme number and Und (2 fh Ye ate: tage enpt 40 auiccals an care ee Routine Jor soprate chafrety hash joble | | pesrtim Fad (sae key » Bath jadi 4 | | { | posftioo Pp; Spree nota XP FL; | | Lit L; eo ° | bm op phe bibs CHash Cmoy , ¥> dapusize)], | Prb Drm; wus Cpl= worl gd bro eramaet +key) Poponets setun_p, present routine for separate chaspry auntie vad Preaek Cur Koy, Yathtake > { | 1 pos? lxo pac, nawnoal; LBE Ls | | pos = Prd (aay HD \ iF C pos= =suir) t pewnccle = mallee Caizeef Cépuck Mocoy: | TEC rewrote. § =wutr? | te yotmulicrs Cueah CKY , 49 fabeowizeD]; eww pola. ) ROLE = Lone; | neonodls -9 element = Koy, La ncat = = nono 7 | . 3 J | Adwoneagel | | ge cotuicion werolution GB sfuple and ope Uneak | eee ay ob etemens can be ced a dt axel of [fred (Ue | | gayle size nicl no} BE Prime Numer. \ * dvtobion A eouy -ro spertaf Flog: voles cas acaoog. | obadwont ADE YEAS porter , wich occup x gas etsments WS apt es olbspPbuled .S orn \ Aeration may haut rane etdraerdt, ome Mout not hae ee fas mma effort te pOferm a canxch. sca x For come langenages + oreadigy new poder Char. 1eridcol (ais) PS oxponssue ard oQoves cow Tue ayarem . | is nore, ONLY | 4 pate, ny ame open caddrter t : | coutedo afth [fnmd (Ut. an oper adeuremrng Poahey | spate «if a elites cou? leonard wud] an enh} ceu fourd . | we gar pred, fo sues polittrds uo Littin | eet | ey [4neax probirg pet) =? |] cyQuackahe probry @ poubu haairy Hath, Ca) = Ro nod R | + A oul fo cate of conttns | Here probing | prbtig & tue procon of geterg pene auarabls | hodh fable ova cell. vB bean pwbig Fa (ener Finck of ¢, | } typicaly EW =o, voluich means deny eels sequcentioley | *n search of an enpty cele | % roo prebig yesolues eoluteeéo pPlact yur clate | Pro Jue neve oper slot Pr tue fable. Pf tur fable reaches | end, tren qu Seach Fe eonfinued from tus begronteg Of 7 Hash Functor cx) = 2c nul tablet/ze , | Lereoa Punetien fPu=t and 4 ov | gs Frick _©4) te, ua, F8r bg rahe | otgy ode oes |e” | N | I | | 2 | aa | aa , 4 a |e [ea [er [ee fea Trial} 6q B inserted at pasikeo @, thon 8 & | | pneented “Gk &. tee Fd? celtics occws wher 4q@ & Presta and 39 ea pue pts nove awalaba paciso | namely ©, WWCh B & a | da ta cay) 68 couice wth 18, 8&F ard thon 4g bofowt 27 empty cole & qourd. The cousin Por 69 hand Pana oralar manner. bere [rnoar Png: % 1e form’ Cluacen wich depractias tus perforrane Of tae hash RABEL for sherman TREITEMI clara - o& Inuases Hur ceasch tre. | Buaobvate pobre | 2t B a eoluscéo peso ti metus frat eleninale | prone Cus teLng pobium af lincan prbfrg. : | | ath auasrazic probing, rather than rune ore slot, it | reowes I> from dhe porit of colts wo PB fee woof aktenpls foraolur tte colts: | alo auadbadie probing pa a las Funct? | | fat? mode Wet) Fb be | rate a apel came Ta [ore ee | 7 | 4q_| #4 44 | | 58 5B | 6 | 4 | | | | | | | —— | ) ° te (e té l@ ra ft | | 1 4a | &4 _ 8q — | | when leq eoicls ak eq, Tw neve qpocf Oe | aktenptul & ona cetl Crd)2 (Pores). Ts OM | snpty so ha B Placed + NOE 5B pW oe | | postnbo 8 tHren ty cell one aoa i pred (ew = Pa) | but onothut hares opceus. That Py FU) = 22-4 lh at cou C 5 A vO e ¢ ff pachtiors | from tg), tmseot 5% ok portion 2.74 sans fry hopper | Lendjabion_: aleexrats. Loca fons SSP Macha aol be uel, 08 oe eousseors- ete & aeiawlt fo tral ty Se, ponte tue fab | an Fu. THA problem known ak 32 tay alike clertond trad resh nO nort thon | UL i | OS be probe tus fame altunadue colts. | | porwbte proshng rouble hashing use Cue felon of applyitg » o 5c Usthe gov hash Fundion’ fo res beywoken a, colt’ abt | qr rest Of FU8 gevore| ash “fecctiso CoP Be fue ruuneber a pesttions from te poe of coluisce te Insert | The prsertin Bb baw on — dath¢ I= oc muwd abt, On cobe 4 colucubo Hus Chore & , Hoh, (2) =e ~< Ge med &) Heh Funcrn. | | | Whee Pod rus prime numb maller fhan dabiesre | Wicap= C YHOO 47 x Hy Cay) need farbee gree ih BI) 18:44, $8 664 € [ [sepe[ ote [ote [mtg Totes" [ote bail ° . : 69 ue ! | | - _ i sR 34 fe _ 68 | 58 Sof 4 ad : af et eee vex ts ~ Aq Ad gs Lt aaa ots |= | tg ae | l@ Bes SST eee a Ta | ee |S Te a No coluren fo Muerte Bq ian) IB E Livst CoWli6o eccurs ab 4G * el Hashe ag= 7 —(4q mad WD = 1-8-7 g so insert 4q ak 7 posiHons from 67 nett wiUisian ab 58 Hashe (qa) =T—Cse-mod Wo 7-2 $0 Prine tus olomont BR at & place from 1 &. medk colftien at 69+ | Baths (6a) = 7a med DY = 7-65) | So eno fru etomend 6% at one [2l0CR / Prem gq. h-L dott ssod ud futnre wo ten Bons a dd mom NS om /9. ° [ pehashiy TP tie tebe gets fo full: flan tue rehashing mubuod bailols now taba drat % abou free as br ond | Man gown fur encind orginal hah fabl. » compueMg | te now path 4 value for each /elomot ard pneexerrg je m gro now tebe pohas hing. 3 vey exponsius operation, tus runny fima A Olw), Afra thee au w elomonts 0 rebath ard Hus Habu Lio 3 reUgoig AN: | “paper boos —for—otetaited —Coreads- Exlencible Harun eo -anerdibts haahig, o. hash dabu & Stored fr tua matin enanog , oad buciols aus Atpored Pn Hue | UB. cach valu @ tue hath fable & a porntty jo a | buanet Pn te seeondoay morsory , | a [coer] co 0 Jos Q00 to 104 joo) 000 Je7t ooo, od! 016 oo Ol =. Loring sorsing B a process of [feeen STG ap Lise of fects joa ol algerie & an algorithm That Pues etomnants Thue ort a number of SOrtiiy techaiaites Thor of tata clement - __gonri { : | TANS OL aided Ato. Y Internal 2OrrY | Cli) eatynal sores | opteanal gore pn tua rack monary a conepettr F TAKA Plas evamput — bubble 07% | ina otin LOVE | Shall Lore Quik s0ve heap core Bxterral contig = fake pase Pn tH getord Ary morcony of ce vonipluty as tus 10: GE ongees Jo ho Sorted a 400 lage bo fie 7” granygles — mange Sort poyphale moge - @| Lrkeation Love Dt a Atmple coming algonitte - woch sores Me) ovreay] by shittheg clomesta ong by 0” - * encertten sort wons by Iakiny elemonds Poor He lst one hy ont. add pee tm 9 £hety correct Parition gto & New sor Uist. some of tes ChaHa Ce oF Bt WoL ome of tus sPriplese Praptemoneatioo x Orkentio germ consis @ N-) pasees , whi Ieke the neemben of Clemons tf be cored. Fae G yfiiert for spaller clats sets, bur very rotiiee far Langer (ae « x setter son bb adepHiue, qrat moans Pp seadecees its foHal number 0} srepe iP Gia a paste aly 2orted USE , penta if Pnoteazes ie effsceentyy. we & beter than sololfer sor and Dithbte com earths. Ue spe conptanlte Go (285 Utter bubkte soxeing , ineertten sors aio nequinas a Ringle addlition| memory Apeu. | x UG sabe (ax it cues nor Change Tue relapue | droll of olamonts with equal Keys. | : # gach pas eo tut snsextion corsing motual wil indeoee | The element Aci nko Hs corpele plan and | ac ant -- aci-D , pes cLoing tna Mme. que | sets ocapyilg at, @@d--ackd cue th corte mraz, Peanpo kets Ree tue folvoweig assay, pe[lelala [27 As ue Can ser hexe sd ins ontlon Sort, ue pick up a ard conepanss re with elements of rH, and Puts ane Koy in tes right pla. 5 | 6 2 & 2 5 has notheg befone Lb conposat & 6 ard b Priented ‘betes i Gf peaks ten -§ and 1 ineexled afey 4, Piraly Lorte4 B Ze poqunrtes G(n-1) pares pinta den an of Dbenents ane. wo alongs 2toy evith tH sesso an Wey. | ingoxtio sort Cine at3 , Ut 9, fr (eco; Cén; CHD t ue tenp = acc]; Pr(f=t-ry jrsos f-> t if CacjJ > temp) © acjHl sag: void y beat 7 9 agti) = tenp, comptonii pnallyats Of S08 sober 200709 oon} —COte Gfme complexity Ou Bese cae Hme conmpteaid och) gs Prarage cage dim& conep otat) space compat —: 0a) Adrancage _of preston _covt mae * DE & one of fuZ Sample SonHng Pees 2a atl cate Smad UE,» x m a ; KI Leverage Fr pie sence of ony ons 119. soot Patten fn He (bse, TRUE EULHAP In BEES HH Ue . Lemilabions of Prsestion vert ; ye eth ue Otns) B wr eu eusted for aged Sif ctemonts fede S . Tw Smalley op te equa (ago no ot liteed ome bey qe gore te pwopely Plac trem in Fig corsece positron. @ Quite vert Ou von F Tur most etter Lonel SOTA teepn que - seas fur rams cuggebte, Some auf Use vey Quuicaty x Quite ton Bact Bde searcp, but tt DB vesy Past and neqinnas vPY [2% addkfioral Apace- PE & bated on rue seule F DIyiet and CRRUR . #* 2EB abo catlod as Paton - exchange Lore - THs atgontim — Abvicls tus lisp Info Vhecoe natn posts VY atemonbs dees Than The Pivat element C2) Pivok etomoat (3) elenents gals than tue piyos element Chor pivot ur Mr Kee value ; Be can be any Clement Po tee LOE) * wow fue Pivot etemont ch plated in SK eorvece Pectifon . yow Tue QuicKcort Pyocactuxe c appued for left subassay and “Et Seth asec FP a yoeueU.j ud. manne - 7 VO; DE KO KO value tna & solocted .arsd shuttled Condinwores Os per tus Quick Lor atforithm antl TE attain 14 dynal positico m tus dirt - je Que con & Tet Passe corring atgorifima 1 Tr hat an cowantage OF miovint an clement 2 Jrtae leben. fn one move fo Pla fn exace posrtien - Rowpne Quite fore vod qgort L rt 20S, tne hott, Ub r¢TKED Pre indy pivot, ben i (ate < right) z Pivot =2ofes C= geteeys alg Sng 2 wurle Ci aj) x WW Cacpive) > = acéeJ) Cncty wae Cacpivoes K Pocty>piwe and agJepive ad G fej ten swap acid arm acy of OY then swap acfl and alptvory . ° a) s . ioe, {oe pine g @ 20 yo lt bo 6 aT go prvoe: i J SooP actl,ac , G ot fel Sveap C10130) oe | Pivot 7 b> 61 47 40 d go go | b> bf 97 Jo piven fc i ® ao 30 wb 6 6! at Te pivot cs J © B Boy bo 6 qt T° pro ; ' t v vor t u @ o ; Bee e wd wa | Os frf Swap CadfJ« AcpiwtD G swap (uo) ft ae 30% Go) Soo B QT * we Se “les nv lemon H@ached 1 corvee pouftico. ™ pos (ones tran fut pivot $ 1G, corde Ff & to nssoused| subarsa, The element realy fran Plwr Poop, quwy & eontidowd a3 rey erbasaoypR qaorte prouduse & appued reeundi vel fer both thee av0ayft (© a0 304 4o s© 61 Qt 70} pe FU pivot f d ¥ @ e& et 0 Me om i 1@ 304 Gi ag | co pit IJ Prot ¥ ea @ fu a 104 oF to ' prot) Cy Y 6b @ a1 1 yp dor 30 pio =P 7? at 70 ii wig 3 & 6! ~ pre td Swap Cam 10) ai & 6 40 fay Lee ee do bo 6 Ww ey Final gor assay. b (4 2 30 40 66 & TO 97 Program for quick sort #include #include int a[20],i,n; void main, { void gsort(int[],int,int); clrser(); printf(’Enter the size of the array:"); scanf("%d",&n); print{("Enter the elements to be sorted:"); for(i=0;i= afi) isit1; while(a[pivot] < alj]) jst: iffi Poform bebber fr sia} oe Lek - a Guttucort otis DOF HOOK seu welt en atouoolly mace sorted (ab 4 QUIK — ef WOM on FUR CLEVE cud ~conaue, Prineple. | ——— Nog sort Tho pest common adgerttim used in eptanngs, ous) the marge sore # mage Sort Eerhnique & baced 07 obtyicla— and — congue approach . * IN mo~L Sort tue unsorted le B ctovined theo ‘n sublists, each having one element, because of a lise of One -gtomont & consfound Gerted . Thon 16 stepeatacty merge Hite cables . 0 Procluee now Soried susie » and all Cates One gortad (de & produced. Tre basic merging abgorithn Jayos two MmpAle anata A owt B ard an output c. The fite elemont of 4 | & sired in gre oheput assay Tux corrersp oralteg potrion A fhoumentsd” i a when enther Pnput a evhatstad yes gamatooley of tHe often assay G copfed fo an OlLeple aie? C. =SO1+ APNE veld moxgesort Coit acy, ime tempt, me nd ard B co conipaxad ,jnen Tue smallse etoment | ; meort Ca, temp, 0)N-1); vod meort Cece acy, me empey, ak Wie» mM TEM) Pre conhtl j WE (date < rgee? conte = Cught +Lete 127 Meort Car bermp, Lefts canter); MSort Cas temp, conter+tl » right); gd MR Cae camp content), nigheD; enter sh ns an nese moge pours T, Fide Leber ent Con merge (Poe ac, Te bentpe uegne) Tre 4, Lend » ny tmp—pas; Rett-ond = conter—is Emp—pot = dope Ne vighe — Late +); WOW CC daft <= Aett-end’) Ax Cconter < =79teD if Cactefe <= acento © ceupe Gxp—posJ = a cleted, Emp_pae +4; 4 lett +45 one A bem Cemp_pary =a Looby; timp pot +45 3 conta +h; uals C Lae < = Lete-end) Tt temp Comp por J = acted; oe +45 3 Erp. pat +> wWe ¢ centy <= Tpke) 1 tonip Cenp -posJ =a Ceena; corks +45 % tre pas +s for (C20; CX ett) q 4 ae compa 5 ® ee _ any ener nme enn i lS ES an paws apis Tone aid pacersror Petal} 0) oa ud ° He 3 [Tay afel [s]'s7] bfafz 5 sey ae py aes iy Pt 3 by» aa ate (E} a eum [a Bt * [27] g fat [Ts pif Brae & [er}2[¢Je} & Program for merge sort #include #include int a[20],temp[20],i,n; void mergesort(int[],int[],int); void msort(int[],int[],int,int); void merge(int [],int[],int,int,int); void main() { printf("Enter size seanf("%d",&n); printf("Enter the elements to sort:"); for(i=0;i on) spo complonity a Aduantagos, * Ba gimp seagoning Fechaiqur that ts % te Aw not veQuina tue UIE to be corted fn a pastiewla? Oret . Di advo pb29Os XP Quit. thetfftert tor lasge sixed Yin. & De ddes not forte. tus Presence OOM pro~ existing Lert exotan in a Use- linear search #include #include void linearsearch(int {],int,int); int a[20],n,x,I, int found=0; void main { printf("Enter no of elements:"); scanf("%d", &n); printf(’Enter the elements:"); for(i=0;i=0) t prune C" olomont & nor ford "27 5 patente mid = (048) (224 acm FX % 3g 444 yen. 30 seasch IP fue mgt Sub axrod » tow = add +) 2 6 77 ha] 11] @¢ | eo tow Te al wd = ea) |2 = 6 acrid <. Beg => 11244 Dyno $0 Saaich In tue Ut Subasoay ; 5 [ I aa | sa ugh mid (ec Lpey Gy chy vo acnid ==2 2 AG Hhy AY. emid-) Mens tow | eS peert thot plarwt 0 found ae 1% posstteo = (reid? & | Ean d Seasoh (1 fiom tw dame sonny. oe 6 Del Tes) se Ges] i] ona aoe wad hgh as (1th Lon than midolle olomem mer | Search fo lett Subasiay ol 4 atm] 2a 88 a 2U7 SD faue acMid] = = = fase otmidy +2 sy hpi KB >t s> ol 2s | Geeerearctty ama wb toa Maye nid {0 + Dom) aCnid] 4% DD weary dyed. dows pid = 94) gy 2 Corpo ty sy CN nut 248) [2 o0 Cocmdy <2? >We atmdJ ==%X 2 > lit+-) ayes prank ab elerront & Jounrk at position 2 (mld) @_ ———__,_— wore} pes Bre company : Beate cage. He campleatty Average code gPme Com prong Spec. complorti Aduantages je De vequinus (ers -ruumber THetton © 2h wou fast sina fe apes tur . ‘olevicle 2 Oonguers) mettisd forgeareh tue Ube. x Por (ape lists binary” seach Wo ruuch fasty thon brea search, wd provoke . @ we UnLk, Was geasch Fe vequines beer, so0ach can be performed - 2 orth wile fer Small lites. binary $203Ch & noF Ww ok Be A not appropriats for (inka) UBL ShuceLoes Cro vendor aces? for tne micelle tem) fue Use to be sorted ee ! binary search #include void binarysearch(int[],int,int); int a[20],n,x, i, low,high,mid; int found=0; void main), printf("Enter no of elements: scanf("%d",&n); printf("Enter the elements:"); forG=0;isn;i+4) 2"); scanf("%d",&afi]); printf("Enter the element to be searched:"); scanf("%d",&x); binarysearch(a,n,x); void binarysearch(int al],int n,int x) or (low+high)/2; while(low<=high) { if(afmid} ‘Calls the Min) fonction oienify he locaton ofthe ‘Swaps the ama elements to move tbe analler elements Efficiency of Selection Sort Assure that an array containing n elements is sorted using selection ‘Now, the number of comparisons made during first pass = n-1 1260, Programming and Data Stucuros sory space to perform sorting. “The disadvantages associated with selection sor that prevent tbe programmers fomesing it offen areas follows: iency of O(n?) is nt wel suited fr large sized lists, ¢ does not leverage the presence of any existing srt pattern inthe list. 8.2.2 Insertion Sort. [Asthe name suggests, insertion sort method sorts 8 listofelementsby inserting each successive element in the previously sorted sublist. Such insertion of elements requires the other elements tobe shuled |, AL2] a sorted sub array. ‘and A(2] and inserted at an appropriate poe. This makes changed. Ths process is repeated untill lustrates the sorting of list Lin ascending order using insertion sattechnique. Sorting an Searching 281 ortonio=uy 78 reads lw porordap eayuodye ax sosn af “2 wf anbruyoay SunOS wonsosur syuowoyduns 7g mEsBOLg ‘sjuowo N Jo Aeu uP uo 0s uonasur uLopIod oy wesfoxd Je aN gg ayduMEXg wom eg ordurexg “suoutay Jo Kee ws 08 0 sossod [-u somber u0s uopzsur ety ABs UBD OM “souopy siotyo ont yt eos on postnbos az sossed oy uowersnt ax0ge af 228 HED 2m SY vojeos wane 99 so0H" = O) sum gr pm 0p 98 SRB ap il ae ‘uosuoposuy TAIL ‘The sorted elenents ary stored in a ing order using bubble sort: 7 pols of nserton forthe element inthe ated sub aay Unlike selection sory, it es not perform a “Aswe can se in the above illustration, four passes were required tosorta ist of five elements. Hence, tedly compares two consecutive elements and wwe can say that bubble sort requires n-I passes to sort an array ofn elements. cy cng eer : sie anh i TH oe sal rapsctctoeowat ie | Geample G6 vinanaieno pint nrons ena fia Sorting and Searching 265, £264. Programming and Data Stuctros toe nage in {1-4 = seed ya ty spe suosuedio Jo 24 RN ios agangdisn poyos si suouo|» wae 09 Kes ee ounssy 40s a7qqng Jo our ul pe vos a 2d 0 swage See ap sons ‘nbuypas Supe oygqna fo wonewueusyduy gg esos 4 au or prsdap wayne amy ssn “9 anbraooyBusy0s agg suomogses 9g wHs8O% ‘wmawa[a x 50 Kee ue wo NOs ajqgng wuopied 0; wesBOxd WAN ‘Number of comparisons made in second pass = n-2 [Number of comparisons made in lst pass = 1 Thus, eff =O iciency of bubble sort = Of") Advantages and Disadvantages Some of the key advantages of bubble sorting technique are | The efincy of) isnot well suited fer ge ie i I eseteneess sae cos creas | Sitters detecns the two sub lists tothe left and right ofthe key value are processed inthe similar fashion until the entire list becomes sorted ‘Consider an array containing six elements, as shown below. large nurber of elements tobe shifted. 7 in execution as large elements sre moved towards the end ofthe lis in step-by-step | 2h Pant ua 2 3740 Initially, the fist list element ie, 34 is chosen asthe pivot element, Nov, the Hist s scanned from | right to let swapped and the list becomes: 268. Programming and Dota Sructres identity the frst element that is less than 34, This element i 2. So, both the elements are 2 ws Moo 40 ‘Now, thelist is scanned ftom ie to right til the place where 34 is stored and the contol stops at the hit clement tat is preatr than 34, This element is 99, So, both the elements are swapped end the list becomes: 2 3 2 0 Now, the fists again scanned from right to left starting with clement 99 and ending a element 34 ‘Blemont Sis found tobe lesser than 34, thus both the elements are swapped. Nows the list becomes: 5 Ho ST ao xe are no clements present between 5 and 34, thus we can assume that 34 has attained its jon in thelist. wo sublists to the lft and right of the pivot element are identified, as shown below: 28 [Now each ofthese lists is processed in the same fashion and eventually all the elements are placed at appropriate postions in the final sorted list Example 8.8 Write an algorithm to perform quick sort on a given aray Example 8.9 Write aC program to perform quick sort on an array of N elements. Program 8.4 implements quick sorting technique in C. It wses the algorithm depicted in Example 88. Sorting and Searching 269 snes prog sedén pov paog Joxo4 Youd 3 16 ou om SEED = ‘pampng wg poe BomwerBoy 01z anbjuyoes Bunsos mb fo onewusueyiuy ye wesBO%d —neoeey | = ieee quick anton a porte nett of | vor, UB and LB values Efficiency of Quick Sort Assume sort technique, Let us analyze the effi best cas, the pi the number of el ‘Tus, efficiency of quick sor in worst ease scenario ~ O(7?) ‘Advantages and Disadvantages Some of te key advantages of quick sorting technique are: 8.2.5 Merge Sort € Check Point a tis the best case efficiency of quick sat? ‘Aus O(log). Fig. 82. Mergeart sorted sublis ate progressively merged in each pass to ing ode. Bet ead = ize cali edule aeeaes Soring and Searching 273 sunpos ya pu Byers 942 ‘porno Suss0s ges paw sey 8S“ ‘aw onbyayooy Bus ofsauJ0 sadeyueape Koy 2p J0 20g sabimqunaposiq pun seboquDApY wl lzlale (WB) = pos ssou yo Kuen “nm, er foc juz fo| > (W000 = eng paves oq = {s8¥ou = apex suosedwo Jo Jagan 0 ‘SUH, ‘patedoo az suatoye 2 dbs YoVO UH 'MON, Woz = sdaxs yo equa f0, ole lzlalz 1880] = sm omy Sure poambar dys yo soquum a, alse |sz || > se1ena 183 = 54 019 Spun 3p parmbexsdzys jo 29quiny omy “ON eee pyesous sy uouo 1p suet om ynun signs 3o sed Supe wo sds0y amnpors “queue 15 nip omy feaneuany pores ane yoe9 vowoy9 200 Jo ssy4Ns asap Uj 8H om Fempeasp wo say eqopom 24¢ S2ympougns OA OF paprA st vos oBsoU ‘uoes APEasE Ona am SY “onbyUoaY ‘ioe oun Foyn pouos sj quawiyo « FuurEWO> deur UE eR ounssy 40s abLoW fo AouaEUlT ‘1248 Smo 10 posn o¥es}2YoNg asaKP AY SHONS p' AMITL"YOED SHAD wa oxy usaagoq ame UatH2]9 68 aAoge xp oT parse pan ee pan Wea aan ‘Symqnonaed st anbeugpy sr, 38 pouos oxy 2320380} pofous ae staxong axp [$0 AUD] “Ps aT sane oo eng Bd nono npr Bena to as ee “wos nb 1 yap my aossoy ApS st soUBAOSIOd ‘qoundo éyvou arv wos ofan q ape undo Jo soquinu om NOM UAT “Z srt andy ‘2330 a2p8 aq, Su0s woped ‘Asowow evoryppe seuinbox a +1 “As wecan seein the above illustration, thelist clements are firs distributed as pr ther values across ilfennt buckets, Then, each ofthe buckets are individually sorted and later merged to generate the original sorted list. Example 8.42 Write an algorithm to perform bucket sort on a given array of integers IS! Example 8.13 Write a program to perform bucket sort on an aray of N elements rogram 8.6 implements bucket sorting technique in C, It uses the algorithms depicted in Example 84 and Example 8 ee cunares pu apes ‘aes seun © ut soawoye BuACy ss azts ABI 19 om SION LZ 2st 29) Uf Soyea aarnadas so sopso oun season a] “| ‘rv anbrasox Suios yong Jo seBeweape Aamo aos saHUDApESIG puD saBOIUDAPY (20 =1H08 png Jo fosayuge 2809 0M “SU (ado = Soros aso 0s dopo Bus ewes st yENG >Re KON “song ofBas ur poe 9g 8 29 Jo EDU HD 10m 9 HL nba 08 ong Zusn pono syeousys a Fmemt0o Kane we eR sussy Bupsos yong Jo AouoroUh [Notice thatthe numbers were added onto the list in the order that they were found, whichis why the ‘sublists above, Now, we gather the sublists (in order from ‘the 0 subst to the 9sublist into de msi ist again: 2, Ierequires adi ‘operation. ‘340 710.812 582 493 715 195 385 437 Note: The order in which we divide and reassemble thelist is extremely important 8.2.7 Ra ofthe foundations ofthis slgorith. ee ‘Now, the sublists are ereated 9g intitvely (Here Radi Speci to the first leter ofeach names, tat is, the names are tranged in 26 classes. nptively, one might want to sort numbers on their most significant dit RADIX-SORT (4.4) Tfori-ltod 2.do use a sable sort to sort Array 4 on digit ‘But Redix sort do counterinutively by sorting onthe last significant digits first. On the first pass cmtie numbers sort on the least significant digit and combine in a array. Then onthe second pass, the tire nomber are sorted again on the second least-sigificant digits and combine in arrey and s0 on, ‘Following example shows how Radix sort operates on seven 3-igits number. Finally the sublists are created accor spat. The remaining shows the list after successive ‘code for Radix sort assumes that cach element in the lowest-order digit and disthe highest-order digit. 1S 710 195 437 $82 340 385 ‘We should stat sorting by comparing and ordering the ome’ digits: 0710 oe A as the itis ethered up again: 198 340 385 497 493 S82 710 715 812 Tas _Andnow wehave a fully sot ara! Radix Sori very simple anda computer cn doit fst. When itis programmed propery, Radix Sor i infact one ofthe fastest sorting algrithms for nunbers or steings of ees. a Sorting and Searching 283 ez fununes pur Bupos “snooty Aouevons © wo yazeos au moped or uaRNORTE Me a PE"g apdUEKA ‘poyeuquis st uoneado yas om pus pourmass wonsdo|xoput Buspeodssx09 ot} ‘panoy sYHAUA|OY ewok sy Aeue njstar oe un pavedaion Appancodat 15 anja up's g lw UMOGSSY yowesscour SBE alvin i sa jo exe we wo poutoyiad anbyuyoay games sou otp >1Gep 6 ams —ngernerenremernerer rma canons 9g ple Buwuedaly yee -anyasooonsum se paopisuo3 9g at ‘Seaamof{ > Zuyeejueo woreso] ox} Se petamaas oq ta 0 “awa xapur ot Ua Uses 99 oy pumMEg SIO Soren ov om ours axe oxy J 90 Puy os HH [o]y area yng eyoHDoE oe 9K I, "pogpaeas 0g 01 spoou em onfea agp 9139] SIUDUR|D W Burueyueo STU so Aes Ue J9pISUO) “pouumgars juDuoq> 2430 GOHEDO} 28 “govew ## aay pen Wwowoye 3H tn ptm poxpsee 29 7 IUENDApe ak sami "OEE caoqusnydes-49- days vw pus ou sprssoySoAoU aw say) Ut DENS Hy a I SHES AE “a oun ot yomoja we 20g soqazeos Sqepuanbas wp sonbruypan BuyortesyeuonteAuoo 9x) Jo ou J) waeag seaury e's “suo Aq auo spoxyem Styaseassnowea am oye 60.227 asi om jozzs -Z se yons ‘sioqoe Jo zoquin © uo spusdap uoRemys wea = m poms Buastasseonsed 30 ojos ut 18 ep wo yore moe os paoydus 39 uso em sporty Buyoreos OLEATE aH, “panos ausuoj2 ‘29 J0 seeuppe 30 wone2o} a suuryas uowesedo wpwas ay, -yoreOs [yssovoNsIN Me Se PaxspIst09 st 1} espaaoxpo “rgsea0one fe palapieuon st Yores agp oq AH of us wasand 99 0 pangs st waUye yt 4 You 20 sostuys jo at onl? w Ur suas St uauo|e UF soMENN SuNOp o} sro BuGoITOS SANDINHIL ONIHDUVES £8 ‘0s som atos 9 yon se ash 01 810 xEpeA Ass Uoswa! 989 4 OITA ‘olor pood » sr nog xpe "NOs Ise poou Temp swerBorM Aue 30 "ep Jo spur puny we Ep HOS HIpey asd [ezUaB w AsO OF “squos soy ane 0 aroagtp ipa stp “so8usypsopuo Buruos ay pu ‘wana 2q oy spoou 08 ape RI J ad aIANp Asda ZO 08 ng a aeNOY 889] YORU osTe St OS xIPEY ‘SOND 30 STEIP om Uo spuodap HOS XIPEY 204 2 tou sqm ay snogeojdamexo tp -yuea no4 Bp 2M jp pur wosur oxp apryuy suoesado asa ‘uos aay ‘Souu Kwang 4802 ‘Sayojos jo ssooond ous pu sszgns oq Jo suonoany pur og yop se yous suNpHOB|e Joyo suIOs ueIp J2mo}s 2q HD 110g IPIAE“yEnoUD WILD ou az suoneiado aia f puv“suoneiado 21s souut 2p Uo spuodop KIa8ie| HOS xipry Jo paads ou, soBmqupaposiq sage av Loca ion of menoryxoriene Papen ‘Calls te JneorFontion to pesform linear search on the ay arr ‘Compares cock ay element with be valu tht neo tobe searched Iciency of Linear Search Assume that an ara containing elements so be searches forthe Inc lets best case, k would be the ist element it the ls, thus requiring only one comparison. fa rst cas, it would be last element in the fs, thus re ney of linear search =(J +2. +n)/ i 1/20 | “Advantages and Disadvantages Some of the key advantages of linear search technique sre: 1. is simple searching technique that easy to implement. 2 Ttdoes not equi the list tobe sorted in a particular order. disadvantages associated with it are as pre-existing sort order in alist. 8.3.2 BinarySearch ~~ Binary search technique asa prerequisite —it ranged in a sorted manner before search that is present atthe middle of the list Ie there Tocation ofthe middle element is retumed. Howe ithe in the left or the right sublist depending on wl the search ends immediately andthe mismatch then it focuses the search ‘Binary search follows the same analogy 28 that of ‘One noeds to keep focusing on & smaller subset of lowever, such a search would not have been pos ‘ges every time there isa mismatch, ‘the directory entries were not alteady sored. “Consider an arty of integers A containing eight elements, as shown in Fig, 8.6. Let k= 21 be the value that needs tobe searcie, ‘soning ana Searching 287 el ples Gouge wormouorny epuessand dace pootdap ade ap son '2 w anbruar yams Arey wus 99 HesFO3g -suouioe Jo Aen we uo yo: Keug woned | WeBOT PAE Lg oldu — : J “wudonmo Aeue waar uo yortes vag ORE of eNOS Ue OHM 9T'g OLLUIEXT srystocons se paapysuog 5 yobs ap pure paumaar sty *1ZJo fea xapUH OM, yea 12} Jo wom ajppra ox wa paseao9 sty MBE Aton, {eI} St go HANS UOT ‘29 wo posnogs st yas omy “Eg wep 8] sy 2001S" SAN QNS Ny ON UE HOUND APPL TL, “sgns 8 amp uo pasnooys yosees ayy] uni 010%8 sly aourg "a YM paseo sty MON saqorear sng. "T2 SEE $1 5! ym payHUEPL SY Kee ap uy EAE. a|PPN Mp Te OSA 2 yea 34 wpseas oy Aaue uo pousoyzod st yornas Kreg oy aqunsep sans SMMOTTO} A, pavios Apeasfe s paunyzod 29 op as Arg oqo. Uo W Ae a 9'§ Bid wt 998 eo aM SY yo0oes Gog 98 ha Program analysis “Advantages and Disadvantages Some ofthe key advantages of binary searctehnique are: of iterations. inder-bnary(ersNXs — recur Figure 87 depicts the hah into. | [ase iterate) ume - Po [ee aay ie | oe ‘0 [ev1 [element Hash key 1 [mont : 1 [rey2 [semen] Nt Fcton Haan key 2 | Bent | Bffciency of Binary Search Tay —Hash oy = inary search algorithm occurs when the element to be searched is an || presenta the middle ofthe ist. In this case, only one compsrison is made to perform the search operation, 1 | sey! | Element Haan Koy ment 1 [reise a Keys et search algorithm occurs when th element to be searched i continuously divided until only one elements et for ciency = O(log) 290 Programming nd Dota Swvetires Fig. 0.7 Hashing [Lotus considera simple example of fle contining information for five employes ofa company. ‘Each record in that file contain the name and three digit numeric Employee ID oft employee, In ‘this case, the hash function will implement a hashtable of five slots wsing Employees asthe keys. “That means, the hash function wil take Employee TDs a input and generate the haoys, as shown inFig. 88. In the hashtable generate inthe above example, the hash function is Employee 99610. Thus, for ‘Employee ID 101, hash key will be calculated a5 1. "Therefore, Namel will be storeiat position 1 in Sorting ad Scorching 294 smal sunonag eg pus unuwnseay 262 umoys coeds 68M Cis Ts] -£ stay ey 9 pena sn ae voyoung te feserom)(o om CB-= Ch 7 <6 aunlig wr poondap st SLL st ‘rasa gsey | sauopsed ond 5 sr hoy ysoy Bunosoung 9 Bk or = Foe Figure 8.12 shows an ilustration ofthe double hashing technique: a De a 2 1 ; ot 21s 4 7 ql a ana) > fl Ss es ail Z|) (aaseanaT a) CD PS Pee 26 Hash Function am afar ‘e Th? Las * 2 la Figure 832 Dole ashing Rehashing When the hash uble becomes too ulin open desing hashing, he sucessv insert renee, Consume more ie to compe. To overcome bis situaton, the retain tela is sree hang wcnigu,atgge emery cuss. approximately twice thse reserved as son Teofal Then te clenents reeked te now st Ts, ' rime number S"belee aurbor spprotinately twice as | ian] OS a tninng hig conde of te owing Mah eon P ‘When te caster ecoes hal fll } ‘When hha pefomance gos below a pre-defined threshold valve | | ewe’ 3 stove aniston ofthe eng tac: Figure 8.11 Quadratic probing | inp ola tba ion, double hashing technique is used. euses two hash | 4) fr | HO hese] Te | SE] retinas 7 8 | t a | 7 crates towards computing the ex avilable action are gven below: | 2 | Figure 813 (2) Betating hi) 296. Progamming ond Dat Scr | Sorting and Searching 298 sz Saucitos poe Caos | semenag weg poe usestong 962 | -andapyeo0 pqs #1 yong tp Jo do ap uous aE } 166601 POE LOOOT eBay cag mang exonq se xp aus. oF Pan are ym) JoquIRE nda ep Jo 1G oun igenonestoymdsronsnqouney vorseyyonrnouséaroruntodean OEBSIANHENA | Jo equn Spa "Wop DE Pay mA a Jo doa HHH omen IL « ns s9quun | oma a mp1 pur soyod am snipe saxong wou w ppe uowpKadop yeqor# amy wet S501 s dep [80 a ‘gdp rego an wa dep 694 Suysoyoy (a)Er'e sundt4 = - = a THe], women 71 fey Cote ; i ; a 7 : = : ea S18 andy or pasedop st qsas au, enanp mn OH! OF PUR 9 son ap HOSE SO AT MON | ate Program 8.9. Implementation ofa hash function ido Sebald > Solved Problems Problem 8.1 Consider the following array of integers: | -35187125231631 Create a snapshot ofthe above array at each pass if the bubble sorting technique is applied on it. 3 ‘Solution Tnital array 3518712523 1631 298 Programming and Dots Sructures dhe. 1357 Consider the following array of integers: one Solution Tnital array 74 39 35 32 97 84 Passi 32 39 35 74 97 84 Pass? 32 35 39 74.97 84 Pass3 32-35 39 74 97 84 Passd 32-35-39 74 97 84 Pass 74 84 97 (cored aray) Problem 8.3. Consider he loving ay of ges se sez i8 29 15.45 38 Create a snapshot ofthe shove array at each pass ifthe quick sorting technique is applied on it. Solution Initial Array 35 54 12 18 2 12 15 18 23 35 38 45 54 (orted aay) hot ofthe above array at each pas ifthe sélection sorting technique is applied on it. Sorting and Searing 200

You might also like