You are on page 1of 48
Unul-? Bala strcturt ' Corting Search § : / c ) search algorithm is an algorithm that accepts an argument and tries to find a record whose key is ‘a’, The algorithm may return the entire re record, Basic Terminologi File: A table or file is group of elements. Recor ch field in a table or file is known as record. Key: Associated \ith each record, which is used to differentiate among different records. Three diff nt loys, Internal Key: The key is contained within the record at a specific offset from the start of the recor, such a key is Internal or Embedded key. External Key: There is a separate table of keys that includ records, Such keys are External key: L Primary icy: For very file or table there is at least one s unique. Internal search: “arching key data stored in main mem External seare! SEQUINi Linear or Sequer I searching function 1. First is the list to be seat >, Second is the farger Each searching i The retur’ successful in ap} If the search is parameter calle’ unsucces ul, the dhe have an > defin 4 ei cae in She Computer mee Arnctire + aah 18 a@ rrechanésy a particular. dalla, mee wo }, the emaits 18 2) Worst Care _ the wna darc is 44. tr whrel ¥ ast Compaoulsr onl oly at the a S pare Comblererly > Cts) Levu bien 1 binann Seer Ae Sas. aad dlour P ag te 3 wed b Ik 16 a. The Indev ed seo ential Search: It js another met od to improve the efficiency of searching in a sorted list, An auxiliary table co!!ed an index is set aside in addition to the sorted file itself. Bat itnee \ extr pace; this method is also known as indexed sequential method. Letr, kai key fivee input values of this algorithm. Other values are k index be an arr of kin the index, and let p index be the array of pointers with in the indes Indxsize «/ve of | > index table. N number of records in the main table. Key Record ——_——_ 8 i= 73 ote 132 pels mai ee | 324, = 480 | kg [589 Deletior / 3. Check toAcfhey Hhenumber present at this index is equal to the numbet (tebe seaich) or not 4. VE IE is equal thmsiop searching, Print the value of that index where the Mumber sdoferind 5. find if rene, then check whether the given number is greater than ox tox than the mber present at middle index or not &, ‘fat Ww greater than ‘,e number present at middle index, then skip the process for the upper half part using the same \ _ first step. Except, put the value of first i “4. That is, middle+1 replaces the valu ~ the number present at middle ind and process for the lower half from first step. Except, put th ~i. Thatis, middle-1 replaces the 8. 7 intil the value is found or the it a 9. . the print the index nu crwis, if interval becot din the array Key F The ki given #incluc I ¢ Inuk an adra qn elomort, feu sorted velres | ga Sb bow =o and high = n-1 seamed = ink ({ fowo-+mg) ja!) 4-| Repeat Slep § and ¢ while Clow ¢ high) 5. (rey < almad) high = med-l; else of oy > atm] ) Rees = med tt ' G: che fh (key ze a tml) ) ‘ pranlf Clement 4 ok else t penl{C "clare | F bnd St Need fo ceased, 40 le ] + few = ) Mudl= M arf Hye Mh, tte tee] fal ora mad (tk) 2 ASeiroy 46 > 32 ken decend hall ce HOLN2 ~ Take First hal of isan Giesbion tanga vers me Kdect Bie. rvcidle, Derren 52+ Since TEE ee inte Lhalvesand Consider the a Tenlsn 2M > HE, FE ayn Fand the mid Dome = md = ae Since, @ NE 15 Smaller than 112, de Conarolor the Sub ae Genakon-3 > Array tal o ded Bet Herdun in Bi frye R23: ( Perqrom of Birany Se arch) D>) He irebudk d t € 7) yal meun() Z foak ale ,ign gruel Ona high, dats bc o, é prenlf (“Enlix the Spe af an ancy! seanf ("cb ", &n): 1 OD print] (“ertes the cel merts in anceading taeda! ») ber 7 (h=26 ; ign; it) *Seanf ("-d" kal 1), prenlt ("entor the 10. & be kerr } eG Id", idle tb), foto =O") hroh ~ whi Gon: hak) § mid = (Log 4 bgh) Ja UP (ot = ie Ap) Lo, break | j 4 fg Cal A a) eee La: 6b, 77 2, 23 39 ys Oa 20 and he eo th Sines _*4o> 30, Sever has ees aa | om Coc ie at [neal b Searches 8 ~ b) [pela soe ts | Tontrally,, 5 = is an Gs pe la Fane remy > e me J aes oat almil}s = pe 85555 fowxsrudt] =F dence ae -#% 2125) 5 _ mud) = ET os 4s = CS "yee ae on 60, 66, - Ae s | Sinee 85 SFP Vous has ue walla ) Smee 25 >80, loco ha re (ay One. op ) aaa a aries et le neice are at od a eee deena) cela) oy kd spo cle splayed ) ¥ Sonbing 1 ee a Lechmere 45 Peeters pee, ee Dest Done or lemanching tril which Combe (mean qa 2 Seniconnaphe or ea Use olofinad vole: 5 Tbevalin bared sorting algerithon Coenpax — Aulecton sot — Rabble sot = Tseslren Se _ peep Ser => Reewverve “Lectin, Algesithm 5 Menge Seat “3 Quen sok os 2. «gees C Corvpansg 7 Combes en bance _Prrperties of Srting ° ae and oukplece, com ° Internal cond enteral So eee aN: wvtalalle. ee — e ert aCgeni.khm ie Solon, sy Se 6 s+ Fret find we Smale? ee! Lin Gate eat oo the _ fost pesiltion Them fond the seconndletorne Nee aad clement mn the bret cord pubif’ tafe. s coord penton-aclse Suma nre i Pass i) Fil Qhe bee. AW) Ala] =" 0 ri Bank He en Snfsxchas Then ts 4 net 2 elomanh sured. pond dhe the ~Aubaroy ADI fas (n- AQsrithm of Sele, Sout, | Byst eh a it tg Imfoos'touul bb fend ad shrines 1B elemiuf 1m eaah Pas def iN ust contain the Smale ar the chemente ATK] AlkH), ++, Afr) Bulle wilt Seofain tbs eee chin. Hien td Hy blows shiprreidine min Chk, #4, too) fe An array A Is im meme. “Ky Dew af the Smables- aes ; = HL an IEE cllegr. Pate Sac Sail \ lt aie DOW EEA) ond bi | Tend of the Boxp'} 3. Rodis in) | iat ; a Mn (AK, bao ng eae Ath) aud * (le @ [Sa ae aee Fenolion for Selection Sob - rod nes uid am sunt ( mb At, nd n) Bf) J, menor, , temp; Secnny catmsed) | i can 43 64427 j 4 oo ee sfonde) ee | eae Fran toe = LS | | edgese au 2462 Tay cad) fee tomeli \ to (G= fH 5 jen 3 JH) } Cea Pecamyea nero! ) 4 minlee = 4 lumps AL]; Req 5 | apy =e A [min oe] 7 brunt) 2 temp, Sart Atyorsta mS an hom Com texvls of pea) = b+ O74 Bubble, Sort @ ae ea be Lange tom te Sika bub fumetvon vod bubblesert Cird ACI, int n) ee eeu ae f ZO ens 4 ent, ie) Se ie (aw 74 i)) i temp Ee Oly ESO ee kon) A DIHI= Jem fa Erample o 1 3 4 71D qed ee 1% Pus! U2) geo 10 28H Bods geo a9 lo 4 cs a Gy ace ea n-F-l 34 ‘ & Be sertion Sovk eh Similar to as ttt people Cae, a hand % cand: > Stank with one carl im your Pam} > Prt the nen cand) and insert Hb tly Fla Poppa Serked ordey: tthe coadg — > Repe ed previous skp te alld cond Characteretios eb In Insedbion & fot = e thy alge is e the Simplest: At imple rrou lat: 3 © Basi coll “a Sot 18 effete for sm e Uts apparels ad deda sels which ase! + Sate { - Working of, dns Inserbin Sook ALI <> Nee gone 1% 55, 6 Tey was | Sa Leration 4 >) fl The. [sled 2 Se Terabe 2 > Tleclin 3 > ect | Daly, Sap cin of omy om Comp ' etton Sort 10) Chere noi hence ane nsf In tte ascends Oreles. Means ee thus, sump to and 122 $6 1015 ceded im A sorted sub a He tothe nenf 9 clemurts al compare Ham: = Here, 12 +15 Dons then 13, Clements seem te be In pre hes, no ng \ (esabacamtehes alll eving fener b the nen relemenk which are 1B bith sand poem Correct plece so Sh pagan peleleter) spay Pelsje\2\e | Here agaon | S)iol isle J — Hew, vt sabi Yeo atepsp sls). . pele) cS Sravdion sort vod Tnoertionsort( mf ALT int n) 2 gy A gee ae ee bx (tat ign t+) oe bey = 081, fe fA, whik (Jzo %h AU] > eu ) AtdH) = Aly; f es; AGH) =key 5 i ee “33 > Ma mnthm ends wu no- mes 9 re ae r aia eo j Rost Care The arrery, 4 cer a CA GI okey ) 1» obvays false ef dak is Ae girned, + 0b) 3 mw woal care —5 WS “ver (ACS >keq ) i5 whe Se > Imulom aluraays coeur ak > ocr) Bos ee cae oe aa Sy ey Nee 0 nae pina lees: Sook lee alge - FE Pesdon Bode ant Conquer mebhaf) \Divile : divide. the pad: dade Sim 2 disjoint Subsets s, &S_ * Brads ag fate Tivo hallnes Reowr $ Salve the dubprblems } Recursivdly sot cach Fall artocalid with 3.25, (@esnn) Comquer 2 Combine the Salitimg Lob we have to sont oar aed, far sarcl 5 tabs a. cabrdion for Erte Ll pro and tend: — : ¢ 7) Dinde step» 96 the given acy A ar gro o- one clement i Aw sation Othe spl A [por ai | Sub - oa oe ie 5 Alpe r ed vont) 16 the ovddie, | a) Conger Stepz— Conquer by Aeeursivelay Boke = 3) Combine Step 2 — Pe 2 Sorted Sule 7 Alved 2c a inte a sested Sequence: sae j ace eee oe Bande Sh se a 2 P. G TSA eT] a. hte | ( ge! vt ot | call nes) - f=. een ese [Emap same Sire Ist V4 za Ke! 1 . G a Rep foo, Je tnd si . A=sieisG =e a while (igs mid and je=8) or Whel@ A01)-5 of Cito 32 ,) eae empk e+] 2 eh) | | ae Re a 3 Again cheek White lop Colo £2 284) |-5 j=! » Nebecte step-3 i — whee sa Bex sizp-9 eee =A [is4) on an aia te do —— I Temp -> | Ea IE IL = parce Sep $- Wha ae <=0 ) 91 Sept le-witle Ci (ae Rls eran Gaon eg Fe] temp To) © Any eS [Neo updakd away a> [Ts Dip Sek mk Ea Ait eee a || pohile, (4 (24°) 2 while (2423 )gToe Like _lembEkte] = ALU e+} | taeidabiees gues Pe Le eal ; Tenn [Cheek again Beprie Same ‘si2e arey | 1 f= 0, jee, k=O ae pm 4 A g. welled KAS Jatsl> 2 J q-| 2h CATA) DAC) 2 Ge SNL) fone & Bemplk et) = AGH 3 tempted ELLs 5 ~ & 3 dye — eee k sep spike tosp-Cohile Coc | 4% 383) 7 Then Sepy- EAGT ATS ; ; ual 1 & \ Saw G4) clre — tempf need = birt) 19 = ABLE + a= re “ — ros tn stele @ Again check skp -whlelop (4 <1 44383 Sep 2h (A rig > ACSI) & 10 523 9 Falter L 5? = > aac, TTT a ay iE, Rey Sie Pup 3 3 orl o so) ees G4 esss)arl me x Carn i) Afi) 3 A [a] >4 [5] 5.40720 FP & i bomb [K++] = cA a 2mennk kemplu] = MER a eS v best Ine me é i = 9 hebee —™ u . Again cheek, While Levp kqeect 5 Ja Fhe | c 3! Check slep_g- While (HU 5) Tues a _ bemp[Kt*] = ALrtr )e bk mbls] eA Fo arcana! Castel OF 255 Aynin check Step. wh Cea) Pehle 5 Aq Sano C) ATG 3D pAe Aes a toy while ¢¢ £2 )) 25) Falie 45 none 12: Leazp fom me A ees \ ACu) & Tembiv} and ACSI Ste mp fe new--A > [a 23] 20) ud whik (5 <3 est) 4 = 44 Pee 3 RQ Shes 5 | EmplKtr = AIT me a é = re MB nal A J Ce a aaah crme Size qray ai a Alte4y . jesy ke : nog 3 |lwhile (4 <"S° and 6c ¢ )-53 T al a (AM >A) 3 2o>6-5T po 4. ak & bempfkre “= A Wer] + tempt] = A) is ra bea 23 Ss Ae oe (ae rand Pemb — Fi wena [mene 6-7 — |ebbe— & jai Agnun cheek, hele Lnp(HS 5 oe 7 Ty a tates ctl frome Tobe aay Be chek eT Eo e pir yl aA A Empis] = 40g miss emp 3 | LTT ated v7 8S = [BAPE Byam check siep-s 9 while ss) oT bemplnr) eh ae temp [td 2h en 1 2 | Koo Jemianay , x=0 3 oie CTes3 ad 4 coe) — tae wi] OCA SAH ae el le 24CA LV > A LH])-9: of (S77) > Fabre 6 ‘| ae Vets, istepeplels OO) j ( | [tempo> Se sine Soy NH || ela, : tempo = -ALIGF) mam Thane mls] 8 Aol => I Again ced_capg» hihi <8 onl 4<=0) Toe | | see. Lomb kee] = ALi+ mf nplee = ALite) [Ages cheek wile Vevp Chee % CMe Cress emp fx #2 Leo _theamk oes ee Te BG i] subtle alas a <2 (HB she) > 22 ee Cheek Apia aiuh ule Lip lagacantl 4 Cats) Ses = 2a ten iKHy 2 2 AGH) | inp > Aenea “| Pgcunr check vohile Lin Cle 3 ie rig CAE Satan S 6) 9 Fe mp [alsPlidzalesl ya AN Cheek, while Lusp “Bauer sol Recansivey get Ye, 2 pode - @ rr ST Quae ert eee en de onl cor arias > Cherse an item pewt and parbition the iLems of A [oa3d inks > pars the thecdpied value cow) a7 4) Lam Shak a Spralle Bon ie Care..-4-!) jel pent (a [4 > b) Tem thal are quater one eq En partion Cink ACD, wtp, it a) § fnt temp + te poke

fink con either be sigifmosk of element” of the aven anay. > Sdeck medion as the pi ele ie Loop -T u Ee of (ACO 8 < 0am Le icodeh BY loep 9 pee ye (NSS ep PS Qucene ort (A 1916 » Ex Quick soot eee Se , —— ary= Fossselela co] 70 t i a ; a ng pival = spent ; re 56) feo. 9<6,unD Le *] id Fohalrae. rele eh me. deme fea i: 4 repeal of e i‘ Fioverne. laments from Jz bow to heh es J 0 $= a ~ Pos \ age’ men |=) wap noyeacy ) Vielen Since £0 E10 wit \ i= 0 weo Sime 30 < Pou ‘a Jel since as) [Ss a : me ames | Jeu cinco gaa ee Swap Co Sine RAdrx SORT ] Bachan cl One Siting alembhm Par i o . USER he Aconicce te ef Mlbing names in_abphabHica) | » Whe we have aise = the taclix 12 26 Co 26 burch) heewiuse Dilbert a éughish ale eis Seas alles pipe Ged Lae oo Sealing Jo Joab Syntificant ig & No Comperison kelweon olaty is needed) The concoph of radix Sort ig ts do digi 7 aero 120 4s do ay Sertusy 5 902. Fe se 62 Kerk 34.9 O54 904, 123, 569,892, ss5 308,91) UL Numbs_ Sa 91) 654 SY4s— | | | — ae ss | z| Bi so) 308 Numb | o 1 Bos AU] 23 123 | ; aay Sys Se a Sos | Sér qart He aire tape 14 wha penal 36 {bucket is sorted veal - [ng cl I aah ee fines 0) a ee As ey had. a staning Hs _ Kolbe w wm Be Binw no: of ae Merz. eet mia means more tire wheres nl Aolucion vthsh cakes ti tke. Fa _deahah» Ls Hist Af searching, in time prsports ep! clara te tast oer toate Lape det unciast mol fost solution unt the kok fin a small om nizaicon whee numiacr gf loo. Each er has Uenag ire Enea kline the emp cod _In_an ae ack, ar an mdex mip @ Lhe o p thou bn fe gene 1+ ke resi of heya ox fo) Crm Ree cord ae Vital Emp 3 Tos Reads “op Tee é ee assume thal dame en In cthis caampl i Jiweiaie This mexly a wes i & storage ‘ { Sspp on ite we jus ae ae 2 each sin Vrper. For ena, will Lee element ane this fo Covert 4 S-degch = Value of + So heap g_mechanssm Inte _'2-degct army taden = ee iule’ -heed @feanchion ushich os © xe —Hash tyble and i ey ee aks 1A ea waa cote nde caboose a sh a iad ero go qenrake watnek of the kay C2. digit a» ba gyn ns vie da , Ion eee eo Se ] (SG 2 kegs (rep Pamk Botha same Loeabion: the Te a AA Calliseicm. s ate ae e ©) Dao hash tite On ebemenf- uth sry k is yndict htc) qoak k= Et meant a hash panchin $h) is a at 1 red te calelale the Gadi ak which the clement unt by Wie ust her stead Hash A fen chim la A A fear lion th @ Alffimatocal formule | ase, Q Key, Rroduccs om Prbeg sn Which Ca was _an fedex Gor Me keg 9 the hath able a4 gad, hash fenchon cae Pe Less dum toa 1 ————_ 1 Dayation Patel ee t we ae aa M a pnme Se firs vo la ye betel 7p pees Gi) | Absyays aud dome veloues of m fe e- m should nit be Jao! power FE m_,Atince_of m2 oP thon h(x) 5 just | Lowest ay bs of &. Porm oioels_ of Ip sheulJ be anpold ¢ the appleeskeons coals withideerwal Aumos Oley ley 2 ah etant mdhad > Squ07e Hh =e ae ee nO) = Loe 3 hire Kis the. Keen ex Seppe sth hash table he Loo momen, eg Eas ies S Ky rk, > 124+34rS~ MulErpli cadcon Metived = flan loo (234s¥003: flaw ( Ie (4419-53 = fe ¢ Zi 3 & Collision Resolution Techniques Hashing in data structure falls into ac the’ same index number in the hash problem because each index in a hash table is supposed to store only one value. Hashing in data structure uses several collision resolution techniques to manage the performance of a hash table, {tis a process of finding an alternate location. The collision resolution techniques can be named as- 1. Open Hashing (Separate Chaining) 2. Closed Hashing (Open Addressing) + Linear Probing + Quadratic Probing + Double Hashing 1. Open Hashing (Separate chaining Collisions are resolved using a list of elements to store objects wi key together. ollision if two keys are assigned table. The collision creates a Suppose you wish to store a set of numbers = {0,1,2,4,5, table of size 5. Now, assume that we have a hash function H, such that * So. if we were to map the given data with the given get the corresponding values H(0)-> 0%5 = 0 H(1)> 1%5=1 H(2}> 2565 =2 H(4)-> 4%5 = 4 H(5}> 5%5 = 0. H(7)-> 7965 =2 + Clearly 0 and 5, as well as 2 and 7 will have t] this case we'll simply append the colliding va by their hash keys, e can be significantly large and the hash mplex, also the data being hashed would be put the idea remains the same. shing but it has its own’ demerits. i Obviously in practice the table siz function can be even more co G more complex and non-primitive, This is an easy way to implement ha: ‘The lookups /inserts/updates can become linear [O(N)] ins constant time [0(1)] ifthe hash function has too many | Itdoesn't account for any empty slots which can be leverag efficient storage and lookups. e a good hash function to guarantee eve + Ideally we requir of the values. Say, for a load factor xemumberyortebsects: stored! inl table/size © >i) a good hash function would guarantee tia associated with each key is close to the -der in which the data is sto Note that the or structures) is based upon the implementa include insertion order, frequency of acce 2. Closed Hashing | ‘This collision resolution technique size, During insertion, if a col bucket is foul until an emp s fou (*) R- linear Probing b. Quadratic probing ©. Double hashing a. Linear Probing ‘The idea of linear probing is simple, we take a fixed sized hash table and every time we face a hash collision we linearly traverse the table in a cyclic manner to find the next empty slc Assume a scenario where we intend to store the following set of numbers = {0,1,2,4,5,7) into a hash table of size 5 with the help of the following hash function H, such that a(x) = x45. * So, ifwe were to map the given data with the given hash function we'll get the corresponding values H(0)->0%5 = 0 H()>1%5=1 7 H(2)> 25 =2 H(4)> 4965 =4 H(S)> 5%5 =0 in this case we see a collision of two terms (0 & 5). In this situation we ~~ movVe linearly down the table to find the first empty slot. Note that this inear traversal is cyclic in nature, element during the search we star inal key is reached | 0 | 0 | ie. in the event we exhaust the last ‘again from the beginning until th HOe = (HCD) modi ite ef hash table: i - Woo = Ce med va), thak varies from 0 + In this case our hash function can be con: HOR, i) = (Wim) + 4) 8%) where N is the size of the table and i repre variable which starts from 1 m1 Despite being easy to compute, i performance, this suffers fr oo oy 3 2 on mere. He fatlirg the Same prbnay ie ) Sequence elem ts Get grouped together, which eventually reduces the efficiency of finding elements or empty buckets). b. Quadratic Probing This method lies in the middle of great cache performance and the problem of clustering. The general idea remains the same, the only difference is that we look at the Q(i) increment at each iteration when looking for an empty bucket, Where Q(i) is some quadratic expression of i, A simple expression of Q would be Q(i) = i%2, in which case the hash function looks something like this: 4 B(x, i) = (H(x) + i*2)3N ie + Ingeneral, n(x, i) = (H(x) + ((c1\#i42 + c2\*i + ¢3)))8N, for some choice of constants c1, c2, and c3 + Despite resolving the problem of clustering significantly it may be the case that in some situations this technique does not find any available _ bucket, unlike linear probing which always finds an empty bucket, + Luckily, we can get good results from quadratic probing with the combination of probing function and hash table size which will guarantee that we will visit as many slots in the table as possible. I particular, if the hash table's size is a prime number and the probi function is (x, i) = i*2, then at least 50% of the slots in the tab! be visited. Thus, if the table is less than half full, we can be certain free slot will eventually be found. Alternatively, ifthe hash table size is a power of two and the p function is (x, i) = (i*2 + i) /2, then every slot in the table visited by the probing function, i + Assume a scenario where we intend to store the followin, numbers =,(0,1,2,5} into a hash table of size 5 with the k following hash function H, such that #(x, i) ——~ Ug Clearly 5 and 0 will face a collision, in which case we'll do the following: - we look at 5945 = 0 (collision) - we look at (5%5 + 142)%5 = 1 (collision) - we look at (5%5 + 2%2)%5 = 4 (empty -> place element here) c. Double Hashing This method is based upon the idea that in the event of a collisio another hashing function with the key valueas an input to find wh open addressing scheme the data should actually be placed 2t._ n we use an in the Inthis case we use two hashing functions, such that the final hashing function looks like: A(x, i) = (HL(x) + i*H2(x)) 89M ‘Typically for ai (x) = xtwp good H2 is H2 (x) = P ~ (x8), where P is prime number smaller than PF) h never evaluates,to zero and ensures tha + Agood H2 is a function whic all the cellg of a table are effectively traversed «Assume a scenario where we intend to store the following set of numbers = {0,1,2,5} into a hash table of size 5 with the help of the following hash function H, such that H(x, i) = (HL (x) + i*H2(x)) a5 ni (x) = x85andH2(x) = P - (x$P), where P=3 (Bisa prime smaller than 5) Hyon = 5 782° yy) 3-573 axl - we look at 5%5 = 0 (collision) - we look at (5%5 + 1*(3 - (5%3)))%5 = 1 (coll = we look at (595 + 2*(3 - (5%3)))%5 = 2 (ce - we look at (5965 + 3%(3 - (5%3)))%5 = 3 (empty >

You might also like