You are on page 1of 39
oe} LORE 51 SEARCHING - INTRODUCTION ” pciton of searching 1 partion ® Searching is an operation which] > ds the elements with its location in given ise. tn search operation if element is found in given lis ~ gen search is successful otherwise not. ‘There are two types of searching eal zee Fig, 5.1.1 : Types of searching ‘syllabus Topic : Sequential / Linear Search tr this method the elemento seach is compared with all the amy elements fom fit position. Whea i is ‘matched with any of clement, then search ie topped ‘and prints the element with its postion. "Fist is unsorted, continue above step until end of list {is reached or number is found. IE ist is soned, continue above step until number is found or an clement is found which is greater than clement being searched. We will see step by step process of linear search in unsorted array. ‘Comparison between : 0 element 31 and search element 49. 6 3D ,es of linear search: TR) oan smucare an oan gw Sos nae om star serch is simple 6s or oo ied on ss a rhs algorithm is applied om both sorted ang io | list. ‘ot 1 or pisadvantages of linear search ‘conta this search is not efficient when list sarge, con tel lee 16 and Seach ee i - between : 3 ek Maximum number of OMPSFSONS aN, gg ae clement. = f ~ Conctsion 161 49 | Seles at Re Hl! Result : Compare next element Zi of cet [SS [a [ef] r ome [oli] 2[s [4] SoehBeret _N ~ Comparison between : 4° element 49 and serch a, clemest 8. ~ Concasion 49 =49 ~ Result: Print the element and postion nd sop the serch, ‘Algorithm of linear Search 1. Accept element from user which you want to search, 2 Compare the search element with the 0* location clement inthe list. 3. If both are equal then search is successful. Stop the pa 4. If bth a not egal then nest lm inthe is is compared with seach element 5. Repeat step 3 and 4 until search element is compared with ast clement 6. If none of element matches with element to search, then display message number is not found. = — Analysis of Linear Search feas13 jive. % ‘ Gir complet for the fling Linear search. i ~ Total numbers of comparisons? are N. Thea the complexity of linear search is O(N), = 30 found at location (5+1) = 6. Syllabus Topic : Binary Search % 5.1.2 Binary Search 1UQ.5.1.5 Short notes on : Binary sea a ‘ CEs ~ Concept : Binary search is very fast. seins technique. ~ This algorithm can be applied only on sorte list ~ Mid = MOWEES Upper formate i wd 0b mid of array. ‘Tech Neo Publications. Where Authors ips low A SACHIN Tee cclements from mid to last ‘lement in tis, ; stove steps tll element is found orth dviion cofpart gives only one element, Example ___ Now consider an array ar{7 having 5 elements _ ita] = (5,17,21,25,47,73,92) search element 17, Mid = Checks 25 == 17 no, here 17 < 25 hence search is continued in first part of list. i Blonder ‘ACCEP clement from wset which tobe searched. 2 Search clement is compared with mid element of the Hist if these two are equal then the element is found (search is successful), 3: Otherwise, the lis is divided imo two parts. Fist part ‘Contain frst clement to mid-1 element, another part ‘contain mid to last element in list! 1 search clement is less than mid then continoe Searching in frst part otherwise inthe second par. 5. Repeat step 2, 3 and 4 until clement is found or the division of part gives only one element. ‘© Analysis of Binary Search 4 ~ If list contain N elements then N/2 comparisons are required, = Then the complexity of Binary search is O(N/2). saa Thea pees ay ms eee Binary search only applied on sorted list. ae So sorted list A= {11,22,33.44,55,66,77,88) Again calculate mid j : Mid = oa elms sel? +2 a Mid = 1 wd SACHIN: "les Puatanwal in BSavsin apie norton en search is ae See continue in second part of list. Then Lower = midtl = 3+ 4 _Again calculate mid Lower + Upper Mid 3 6-8) given below: ae Az (Ad, 5, 2h, 3,249 47,2, 455 search only applied on sorted list. 5, M1, 17, 21,29, 43) Binary So sorted list A = (2.3. Checks 66 = 88 no, here 88 > 66 then search is continue in second part of list. ‘Then Lower = mid#l=5+1 Bas Again calculate mid de _ 647 aes Mid 6 L miu (tomene] ax [a2 [oa [oa [55 [os [7 | os estes] of 1t2]}3[«]s]sl7 Checks 77==88 no, here 88 > 77 then search is continue in second part of list. Then Lower = mid+1 = 64 Checks 11==29 no, here 29 > 11 then search is continue in second part of list. Then Lower = mid+] =3+1 =4 ‘Again calculate mid Mia = Lover+ Upper _ 447 ea Mid = 5 Tech-Neo Publications...._.. Were Authors ingpe innovatia ass oD 5129 90, here oF cod part of list, g Lower = midst S+ia6 ests 29 = 29 Ye. Element i wet fon at cation Applied on both | Applied om only sorted and | sorted list. sone ist Very simple to | Difficult 10 ‘understand, _| understand. ral en not wef when | useful when lst is lists long. Here Lower = 0 and Upper =9 Lower + Uppes Mid = 3 on =4 : data structure. Checks E == H_ no, here H 3 that Pe Ve mils nese search techni creased, the Hime es lineal - nae elements gets i clement also increas 1 approach in Wh 1 doesnt depend O° nich time required ¥0 = Hashing is anothe at cements ve 5g ihing dan sree 2 eet searches : svth constant time complen ; ee 1 reduce the number of = Hing isan eve Wa © es Yn ws ado oc 2 eee nea Ma on, delet and seach EY SEI in strvctre Ging hash table concept insertion, deo ay ; process of indexing seach operations are accomplished i CONN ing, _ ¥ eed. vetriaring elomens (data) i A Gata || Generally, every hash table make use of a fg 2 structure to provide faster way of finding the wich well call to map tbe data sto the hash able F clement using the hash Key Applications of Hash Table ey is value which provides the index Here, hash ly to store in the data ‘value where the actual data is like strocture. ye 5.2.1 Hash Table jp this data structure, we use a concept called Hash table to store data. _ All the data values are inserted into the hash table ‘pased on the hash key value. Hash key valve is used 10 ‘map the data with index inthe hash table. And the bash key is generated for every data using a hash function. ‘That means every entry in the hash table is based on the key value generated using a hash function. 3 Specifically, those that require ‘efficient random access. Generally, database systems try to optimize between two types of access mein: ‘sequential and random. Hash tables are an important part of efficient random access because they provide a ‘way to locate data in a constant amount of time, Symbol tables : The tables used by compiles © ‘maintain information about symbols from a progam Compilers access information about symbols frequently. Therefore, it is important that symbol tables be implemented very efficiently. Data dictionaries : Data structures. that sopra adding, deleting, and searching for data. “Although the operations of a hash table and a data dictions * similar, other data structures may be wel © {implement data dictionaries. Using a hash rable particularly efficient, Database systems = | the hash table. 7 ge yor bave PUNE Sony "piling © APATIMENS ang IN Whi sor house, YOU CAN ans asked the Re re thal 1 tg ee isin in xyz, : \iiding OF apartr i ot g OF apartment is a bucket se 7 OUSING colo satry, eo SS folaing lastnoa, Orv os me one a Masi 7 FUNCTUNCTIONS : nasi SQUARONS : TRUNCATION, MID- METWe gr ETHOD, FOLDING HOD, DIVISION METHOD Describe ” ‘Nash function is any fu ra cio yon tat a ee Teese tf a iy sie oa dane of Tel i ain deh a valk ies fee” ‘hash function are called hash re aa ity aes ‘4 good hashing mechanism, It is important 4 good hat function with te following basic ‘Tequirements:, = The hash function converts the key into the table positon cane eae ou wing (A) Truncation: Ignoring pat ofthe Key and wsing the ‘rest as the array index. ‘The problem with this approach i tat there may BOL always be an even distribution throughout the table © For Example 1f student id’s are the key such as tee digits as the index ie. 3 928324312 then 12 as. whole Key participates | the index for the table, thvs, there 1s of finding © citer adaress &¥ Example oe camp, if ve kay you 1621991 squared result is 4835601 peso pt of thi opto 356, wed il NON” be used for indexing into the table = say te sine of the table is 1000, then, 2199) = 356, “That is the hash function using mid — sqvae ca vy valve will prodyce 356 as the index value for Ke 2199. “The advantage is tat the results not dominated bY the distribution of bottom digit or top digit of the exiginal Key value. — The problem with this method is choosing the middle part of the result obtained by squaring the key value — To resolve this issu, itis advisable to choose the size ‘of the table tobe of a power of 2, suchas 2r 50 thatthe middle bits ae chosen — In such a case, it is easier to choose the middle part of the result using masking and shift operations. (©) Folding : Partition the key into several pieces and then ‘combine it in some convenient way = For Example = The key K is partitioned into number of parts each of which has the same length a the required address with the possible exception ofthe last part. — The parts are then added together, ignoring the final ‘cary, to form an address. 7 Example — _ If key=356942781 is to be transformed into a three digit address. P1=356, P2=942, P3=781 are added to ‘yield 079. (D) Division Method = Compute the index by dividing the key with some value and use the remainder as the index. This gives the indeses in the range O to m-i so the hash table should be of size m Tees Pllc, Where Athos pr Imo pies an example of uiform Mash Fig i sm wil be chosen earful og Generally prime number 8 Bt Choe wig spread keys evenly va ‘uniform bash fonction is Gsiped 6 dig eye roughly every nto the aval pot yi the array (or bash table). pris forms the basis of the next two techniques, For Example index -= key MOD table_size Consider key is 102 and table size is 10 index := 102 MOD 10 index :=2 we 534 1. Easy to compute : It should be easy to compute an ‘must not become an algorithm in itself Uniform distribution : It should provide & vnifom distribution across the hash table and should notre in lustering. ‘Less collisions : Collisions occur when pairs of ‘elements are mapped to the same hash value, These should be avoided. 4, Be easy and quick to compute. '5. Use all the information provided in the key. Syllabus Topic : Collision Resolution > 5.4 COLLISION RESOLUTION 5 1 S41 What are ithe methods collision? 2 le of win) the Se is a git eveely eu wa ye swith th erga with them. The Posi 07 4g out the records au see tr MEMOFY @ pore than one reek pot Ord ata sin gampte of Collision a we size: 11 Hast poable FADER Key mg 2 pew positions in tee {he hash table ary 28 ebep Fig. 54.1 : Col * 10 potner example (in a phi c Keys ronebook record Fig. 5.4.2 : Collision Here, the buckets for keys ‘John Smith’ and "Sandra Dee! are the same. So, its a. collision case- = Collision occurs when (kt) = BO), jie, the hash function gives the same result for more © Strategies used for collision resolution 1, Open Addressing in the able ~ Store colliding keys elsewhere in the 1 ice re me beck), {ables (hash tables with 1 oF more M the ee fonction ia copied. elena find another bucket for the ee, “Then increment te table position umber. There: ae three schemes commonly used for probing: 1. Linear Probing 2. Quadratic Probing 93, Double Hashing Fig, $43 : Open Addressing Techniques > 1, Linear Probing she wet lt forte coed Key found 2 rpethod by using a technique called “Probing”. Module, i emcee ee rnin tN? epee cee be poner ster =. eo ‘rashes into a pos js to look for ] i nor oor Aner near ANG ‘Anerinsert Aner insert ANC i i xd [ra 49 49 i IES i jel 2 : [2] +} ; : . , shed ped Ged Ded Ee Fig. 544 Linear Probing — The fist collision occurs when 49 hashes to the same location with index 9. — Since 89 occupies the A[9], we need to place 49 t0 the next available position. ~ Considering the array as circular, the next available position is 0. That is (9+1) mod 10. So we place 49 in AO) — Several more collisions occur in this simple example and in each case we keep looking to find the next available location in the array to place the element. — Now if we need to find the element, say for example, 49, we first compute the hash code (9), and look in Ap]. — Since we do not find it there, we look in Al(9+1) % 10] = AfO], we find it there and we are done. ‘So what if we are looking for 79? First we compute hhashcode of 79 = 9. probe ° We > 2. Quadratic Probing ‘Akihough linear pfobing 4 a simple process yp tasy to compute the next AVAIRBIE locaigg 5 1 also leads to some clustering when jay = 1d to closer values. — Therefore we define a MEW Process of Quajae probing that provides better distribution of.” — tn quadratic probing, ifthe hash valve is K then gy ext location is computed using the K+1.K+4,K49 ee — = The following table shows the collision reson, using quadratic probing. hash (89.1 hash (18,10) hash (49,10) hash (58,10) =8 rash (9,10) = ‘Atwerinset Afterinsert After inser Afferinser Alterinsen 89 18 49 58 TTT > 3. Double Hashing Double hashing uses the idea of applying hash function to the key when a collision occurs. in (9, Al+1)] = Alo), Al942)) = All], AL+3)] = Al), Al(9+4)] = AI3) ete, Tech-Neo Publication... Where Authors inspire lanovation =A SACHIN SHAH Vento He is (Mu =Sem. of the secon result dash an f “or positions. fro ze ™ the pont a Point va te ot t Olson v je 0 couple of ee requireme ms f for a 7 Er jy stould not evaluate 6 ‘cond Nahuatl 16 pute sould MAKE SUE Aha al gy Jar seco Is a R) wher = Hashy o ce R'is a thaeee oes twee ue tan the Size ofthe tbe, a is Disadvantages of Chain 1g) 249% 10= 9.8 colision | ot 7 -(49%7) rv 27 positions froma] LY Linked ae ee inked lists could zatively impact performance 9) = 58% 10=8 ‘More memory uilizat x oe uilization because of pointers = 5 positions from (8) ‘Syllabus Topic : Bucket Hashing yesfen) = 69 % 10 = (69% 7) 5.4.3 Bucket Hashing positions from [9] _ packet hashing is treating the ash tle as Fig. 5.4.6 : Double Probing dimensional aay instead of a inear ar aivided or Consider a bash table with slots that 2 bucket consisting gylabus Topic : Open ‘Addressing : Separate ca tho Chaining Pep ioe = satan cn ssn ward we 1 35.4.2 Separate Chaining within one of the pockets. If the, slot was already the bucket slots are searched ery hash index FOF collided | sequentially nil ~ Maintains a linked list ate’ sy fat the soeord will be conte pence’ : oo eet Packet finite copay a = Las take the example of at insertion, $4 eee : (0149 1625 36.49 64 81) : os vi Here, hk) = k mod ; vemeattion: AH recor evel aE rds as possibl in list at Tih(k)} om rca and poms MU Sa.) iz Index puck 0 | eam | ar ee | a 2 | sat s [sam «| am x B3{l) s | wo 9 | pan Overflow Bucket 48 25 Given this bucket hash table for an array of size 10 storing 5 buckets, each bucket having two slots in size, lets see how this method works in practice. We also have an overflow bucket of infinite size on the right to store records when the buckets in the main hhash table are occupied. We will use mod operation as the hash function Let us start by inserting the number 18 as our first record, Since we have 5 buckets, we take mod 5. 18 % Sis3 We put this into the top of B3, which is slot 6 of the hhash table. Now inserting a record for 30. 30 % 5 is 0, 30 goes ey ewvcture and ia Soarhing wg 9 ext we insert record f0F 38:38 % 5143 Ni 1 placed in BU ext up we have 48,48 % 5 163, but the Bai ence we store 48 inthe first availabe soo ‘ ca oo ty vit 2-20 50 ve Ses ceil be oe Bor Se 2 si 0nd clare toh ec een kaos oi oo a va ies king oa WS ae ia sence rong kt ie cnch fot hy ab 3 theee BaD) which ble «Ae a hc Olan we Sader key es eg fer io ky a 25 we a nly, Wee Ge tld ory ae Te heac ak rg hc ee ft etching O80), hn OB] a wee fa i — Note that if there are many records in the overflow ‘bucket, this will be an expensive process. Syllabus Topic : Analysis of All Searching Techniques Dl 5.5 ANALYSIS OF ALL SEARCHING TECHNIQUES: eh ” ly ae < vs, the most it a oo important hing bat the infomag 0s ieeat (yPES of mation, 4c = : ce sie ESBS iy : ts ue o Feached ec es rn Her re the ts to search forthe bill : heik ase forma ten Mo is quickly otherwise ye wget searching wii the ask and head: will be a os lache for him. os come 208 SUCh EXPEENES may fo uy ie. Number of 6 my Set mens sly and quickly at the ae ered ‘when suis bapgen Because we don't Keep the din ia sre rma Hence sorting i vey i ‘Minion : Sorting is a Ge the data elements rc p rearrange ce form of ascending of de e| arer, which may be numerical, lexicographic | rang user-defined orders et ‘The importance of sorting lies in the fact tat 1 et on tit ape re. word ealy nd fast. Fig 561: Type of YA Antena Sorts = eer process of soning. ~The main me oA a nae {sno need of any secondary memory for Unis soning process = Whenin the memory, a teal the data tobe soe canbe accommodated, then this toring = knw. 8 interna soning. Druwack : Relatively small Tits can be processed pecause of memory limitations. | rere opinize dt ch AF REN ; the data is available in sorted format [rssesionsot | is be 7 hs inert ot na [icmsenen ot | | spmsend ina beter reasble ol * ‘Examples a me ppp of internal sts : examples obit 7D rea tite scenarios, thee ae some : gaection Sort Sec ep st sei gorithm, Shel »\|o = © 1s follows: > 2, External Sorts memory for sorting large amount of data. When main memory is insufficient to store the the extemal sort method uses external memory HDD. sorted data is present. Iater on merged together. © Types of External sort ‘Merge sont ) Fig, 5.6.3 : Types of External sort 2% 5.6.2 Sorting Algorithm fan algorithm that puts elements of a list in a certain order. — The most-used orders are numerical order and lexicographical order. Use + Efficient sorting is important for optimizing the use of other algorithms (such as search: and merge algorithms) which require input data to be in sorted lists; it is also often useful for converting data in a standard form and for producing human-readable ‘output, Definition : Sorting algorithm is an algorithm which contains a series of instructions where ‘array is taken as input, specified operations are performed on the array and gives sorted array 4s output Concept : In other words, we can say that a sorted array is nothing but an array which is in a particular order. Concept’ + There. nand\ of exert e087 Hence in the primary memory only currently being “The base of all the external sorts is process of merging. Different parts of the data are sorted independently and Concept : In computer science, a sorting algorithm is | ~ example: 4#118 sorted aabetaly, 5 ‘it of neg ered in aicendig order, ang 18 je list of integers sorted in descending order, |) data, like za. 5.6.3. Efficiency of Sorting Algorithm i “i Concept + In the process of SOrNg algorithm, q. efficiency is always considered an importan gg ‘To add value 10 the sorting algorithms, We faye y efficiently sort the records. [a Definition + Efficiency of sorting algorithm nothing but the time taken by the sorting ‘algorithm for sorting purpose. Hence the efficiency of sorting is denoted in terms oy time complexity. As we have seen in previous chapter, Big -oh notation is used to represent time complexity, In general for various algorithms, time completes available are O(n") and O(nlogn). ‘The time complexity O(n*) is basically related with sorting techniques such as insertion sort, sell srt and bubble sort while the time complexity O(alognis, related with sorting techniques such as quick sort and ‘merge sort. ‘The bubble sort is considered as the slowest while the quick sort is considered as fastest sorting algorithm. ‘The number of records to be sorted also affects the efficiency. = Passes : In the process of sorting elements in some specific sequence, the elements are arranged in number of ways. | Definition = Passes “are the phases in dl elements are shifted to get the exact position For example : 1, 3,2, 5,4 Passi: 1,3,2,4,5 Pass II: 1,2,3,4,5 Tech Noo PRs {0} uth 48) 33 innoration — Here we can observe that two passes are used to sof the elements in ascending order. 0.2 sr 3.2 G 8 Kities } elements 4 and 5 1 Pe wile i the Second py a ass “a mall ; & ribs proper place, "een 9 hat Cope TOPE: Sort 12 Technique ew _ i, sORTING TECHNQUs AS We have already seen that Sorting is ata elements «which is used to a Fearrange the. prin sanded £0 Of ace y j_ which may BE mumerical, Jey Odescenting werden order. bee hk “per dt OTBEE,YAHIOUS OpEaton ae per ua 2 pet FAICEMIEDE SUCH 2 insertion, S posication i the records. After seston we need to sort the data. a yn structure provides various techniques to son unin required order: F 4. Insertion Sort Selection Sort B. c. Merge Sort p. Quick Sort E Radix Sort. 's Topic : Insertion Sort <0 Ween Postion cement re iid oe Mag ON 8 win compare . Le ee eager wh R 1 Now clement rmsider an array a(S} having WO ascetic Fig $7.10) Comparison “ - between : 1* element $5 and (* clement Conclusion : 55> 31 Result : No interchange. Iteration Fig 57.10) ‘Comparison between 2 element 21 and O° cleseat 31. — Conclusion : 27 <31 Result + From 0" position syllabu: een ce ie the 1* position Position element, thet! 5 clement 31,all elements 8 Ylodule = ‘After completion of second as follows Fig. 57.100) Fig. 5.710) — Comparison between : clement 16 and (Of clement 27. = Conclusion : 16 <27 — Result : From 0” position element 27, all shifted one position right and 16 is ins elements are serted at O* location, Fig. 57.10 between : 3” element 55 and 1” element = Comparison Fig. 5.7.18) — Comparison between : 3" element 55 and 2" element 3L. = Conclusion : 55> 31 = Result : No action ‘At the end of iteration II, the list is: Element] 16 | 27 | 31 | 55 | 49 — Comparison be — Conclusion : 497 27 — Result : No action Fig. $7.10) ‘Comparison between 149 clement leat 16. Conclusion : 49> 16 Result : No action Fig. 5.7.10) tween : 4% clement 49 and 1* clemen, 21. Fig, 57.106) ‘Then, 4 position element 49 is compared with n position element 31, here 49 is greater than 31. . Result : No action Fig. 5.7.10) Comparison between : 4° clement 49 and 3% lem 55. - Conclusion : 49 < 55 — Result : From 3 position element 55, al elemea shifted one position to right and 49 is inserted Te Aas ee uhm of Salve Insertion sort. ion Sars with omy (a ee. of lociion elena at wil jon element in the a ‘ment is less then it isi one dental a ae mit location element is moy anextlements. wae ooo of previous small clement andthe pson of previous element shits Oonipeiion tea spose procedure 1 TDs Kaas as iit. ; I, gssisis of insertion sort ‘al numbers of comparisons’ are = n(o-l)/2 = O() 3 5.7.1(A) Examples tpt, each element in the list i co pious elements If the element fee all emis element then the clement is j any inserted at nel) + (1-2) teed HDHL of Insertion Sort a location im cation a \ a els Te ra rotitatstetsts {\ [Bemea] 2 | s Peoas oo [se] | lrommo tata taietstel (Gen ss pets tal ee etrtererstel © ‘Searching ang 520 iteration | i @ Iteration i ®) Iteration Ill amon jaar] a0 | ao [so 20 [as Pome oo a2 ots (cane oP s00] «0 | S00] 20 [as eee aoatons [asia steele [siemens] 30 [20 £ aac pseeen Poslers|uas]usules|an © Iteration IV 0. Fig. 5.7.2 E76 Elaborate the steps for performing | insertion sort for given elements of array : 20, 40, 40, 50, 20, 45. (6 Marks) ee eB Fig. 5.7.3(€) 2. Selection Sort - Goncpt = Selection Sort is considered ste snp xed of sorting. res — fe algorithm divides the input st in two pate ‘ered sublist and unsorted Sublist — ly, the sorted sublists empty “abs isthe entire input Hist and the unsorted ). The 0 element is compared 170 element is found greater they are interchanged = Hence at the end of first iteration, the is placed at 0 position. ~ Now process is repeated if position. = The 1" element is compare with see IF element is found thant next they are interchanged: ~ Hence at the end of elements second raion is if then 2°" sr having 3 cements 2.16459 cine Wit tera cement ies ae ‘element $8. ‘Conclusion :31.< 55, esl :No interchange Fig. 5.7400) = Comparison between : 0 clement 31 and 2 element smallest element is Pl ~The peoiess in epee $on (1 = an ta Wn an positon a aes 0 Te 62 Data Structure and. qu - Sem. 3 ae = Comparison between : 0 element 16 and 4% clement é ws - Fig. 5.7.4() ~ Conctusion 16 < 49 nan fered of ited A z * ‘ner the completior the Am ve nh stat 827 cons ng mon ofthe sorted is poston, where 55 ro Fee eat of Ge iat (mrt) fed ga conning te 2 samen Hern I fer be completion of est tron, minima vale Fig. 57.4¢0) in the list that is 16 comes in zeroth position of the | Iteration It soned list, =) fete — For the 1 position, we start scanning the rest of the pemeett Ste fatale ist (unsorted) i the same manner i iteration TL . eration Fig 5740) ee — Comparison between : 2 clement 55 and 3" element a S] SSE ao a Algor ~ Conclusion = 55>31 Bi Fig. 57400) — Result: They are interchanged. oe — Comparison between :1* element $5 and 2 element are sw 3 Conclusion :55>31 ae ‘Result: They ae interchanged. pore Fig. 7.408) 3. Inse (some ae) (Sols Parl rest omslo] [a tetsts ‘Comparison between : 2° element 31 and 4° elemest 49, Fig. 574¢@) — Comparison between : 1" clement 31 nd 3" clement |~ Conemsion®31<49 7. ae Result : No interchange. ~ Result : They are interchanged. [samens] 8 spe romeo] [a tatel« Fig. 5740) Fig. 5.7.4(h) = ‘After the completion of third iteration, third minimum. - ‘all in the ist that is 31 comes in the second poston ‘Comparison between : 1“ clement 27 and 4% element eee 9. sorted ~ Conclusion : 27.< 49 ~ For the 3" position, where 55 is wwe start ~ Result: No interchange, amin te ret of te Ist ( a cranes Tec Ne Pblicon—— Where Auth inp anor ‘manner in Iteration TV. @00% ma Nol taN vo a0. Te MU Som, on = | |p ‘ Of Selection Sort. ase Fig. 5.7.4) the Firgp . ote between t 3” element sone oe 55 ang go | Neration pesion 55> 49 wee They are interchanged, Re poe ne ists sorted completely. Fig. 5.7.40) __ ere ae 5 clement in above! G1) = 4 iterations are ae hence (a-1) ee commnlete) i ist {Algorithm of Selection Sort 1, in firs iteration ‘first element is compared with rest of toments first element is eater than that then they are swapped. 1 Ater completion of ed at 0" Jocation: first iteration smallest element is Fig. 5.7500) stor 3 In second iteré rst of GP 10D” Jocation) elements swapping is repeated: 4. If the list contains 0 required. © Analysis of selection 997 In first i second iteration (2) on. From this We Fig. 5:75(0) Fig. $7.6(a) | [eI le lols I eration Ill using selection sort A = {42, 23, 74, 11, 65} (3 Marks) Teci-Neo Publications... Where Authors inspire innovation REDMI K20 PRO @00 Pai o Fig. 5.7.6(@) Fyabus TOPIC : Merge Son yet? write an algorithm For merge sort corament on its complexity, . F pqing 18 nothing but combining of two anys WO ssoutput in sorted format. + Bsample ow consider two arrays having 4 elements > ial = (91,5527,16) Tey Pe cy She aBg=(11,45.9,00) | array A. | somene{ 33. sie ps| tention | © { nae | eomont (38271321554 | ration FA Betoeen tara 8, teen, 13159) N:9\ W tere in hid ary tow i Fig 57.116) > Comparison ‘between : OF clement 16 of array A and Velen 1 of ay B. = Conetusion : 16> 11 Detween : 0" 2p element 45 of aay B- +o semen \6 of aay A and rttts| Fig. 57.10) clement 16 of aay A and - Conclusion : 16 <45 ut: 16is ins intl AT aa sa Fig. 5710) acy Aand yt element 27 of Pe 82.70 = Comparison between : 2 element 31 of array A and Phaemat a5 oforeyB. — Camctinon 3145 a 1, Accept two arrays from use and sort hese aay ig any sorting algo. ee f . Ms “a a Ater song, compar elements a ty A with any eng se lement ia ery A is leis than Bu if elenet ia ary A iss han amy Btn ee dient a ey Ais eres Oe a »ment) as PIV ‘avablof ray And ary C a8 increneedy me piv 5, If Element in aray A is greater than amay B hen pace Pi Fie. 577) an ll Comparison between : 3% element 55 of array A and ‘variable of array B and array C are incremented by 1 variable i pol 2 cdemeat 45 of ary B: 4, The same procedure is repeated until end of one ofthe (o-1)* locatio Couctasioa 55> 45 ay is reached, then the remaining clemest fom = = Result: 45 isinsere in thi ay another aay ae aed to third aay ae Analysis of merge sort Be Saal eee ict pene eeecea eee pol sae oel ed ara aheenieclesaess Jog nefficiency =O (alog ) Be as ei eit © Advantages and Disadvantages of Merge Sort Pay fe amass [alee als Ts decrement Tate found. Fig. 5.7.7(h) ~ When thes ~ Comparison between : 3 element 55 of aray A and | 1, —ttean be used for internal and external sorting. This proc 3 element 80 of array B. ee ee ; . His stable soning algorithm. osher. ~ Conciasion:55<80 f it It very efficient method. ~ Result 5S is insted in third areay. Bra ‘ © Disad aa = After this, element in aray A ar exhausted, then the vantage soot ‘remaining elements in aay B are added to third aay, | 1. Itneeds an extra memory for storing of merged dala Tech-Neo | ti a ss - Pilea Where Ath ip nation’ aa — REDMI K20 PRO @00 Cera ‘yo. ; ott” Find its complexity, yos7t® explain quick sort usi uro_ond Analysia yy 40-Som a gas implement quick sort wi Write algorithm for it oe example, its complexity. Comment on | 5717 Write an algorithm for quick sort and | comment on its complexity i ‘as name suggest, quick sort is considered as the fastest sorting algorithm. In first iteration we set the first element (0® locaton ‘lement) as pivot element. In this iteration we have 1 place pivot at its correct position. Here we require two index variables, {and j- The variable i points to 1" Tocation element andj pons © (n-1)" location element. o {variable is to search an clement ‘element. Here i will be 804) point pits vow 17,2 et dt at an 5 gm teed pf} Senet Fo ha 15, ea ee 15 it will not decremented. = ets tT 1h Ms [sats [al 1- Tal | ea ese Pret i 7 Fig. S70) Hence now valve of por element 6 SW0PPS value of j est case 00108) Worst case 100") Quick sort is recursive algorithm, rinse kin by HCE SOF = a partition + running Hine of eft partitions tine, partitioning == or Here first two terms are for recursive call and last eng 800) ‘ are is for partition. re 15 becomes the pivot clement. We can ob¥er? vc ctedae fer meet avid nav pnt eam) | contin elements: mS ef i pefore 15 are less than it and all the elements next 10 i contains k cloments) thea time of te are greater than it. partition T(k). — Now same procedure is applied for.two sub. arrays: ) = -Therefore running time of right Parition= Terk), ‘This will be repeated until all the arrays left wi single clement. At that situation all the elements will be in sorted form. = Algorithm for Quick Sort sort. Explain with an example. Lowest index element set as pivot element. element and j points to (n-1)" location element. Index variable i is in search of element which is greater than pivot clement. Here i will incremented by 1 till greater element is not found. 4, Index variable j is in search of element which is less than pivot element. Here j will be decremented by 1 tll small element is not found. 5. If these two elements are found, they are swapped. 6. ‘The process ends when these two variables are crossed or meet (In above example they are crossed). Then value at index j is swapped with pivot and list is divided into 2 sublists ‘Above steps are repeated on these two sub arrays (sublists) until all sub arrays contain only 1 element. Write an algorithm to implement Quick “Take two index variable, and jj points to 1"Jocation J 1 th Tin) =Teo-1)+en. quick sort. @ Advantages well as long. 2, Best case time complexity is O(n log n)- © Disadvantage 1. Quick sort algorithm is not stable. Syllabus Topic : Radix Sort 720 State advantages and disadvantages of For paition, needs seanning of aray linearly =n aoe TOTO Den. Here cis consent) Ge Advantages and disadvantages of quick sort : ed (Mara) iene ‘This sorting algorithm is useful when list is small —_—— Radix sort is advanced method of sorting. in maximum number. Here we need 10 packets ech Neo Publications... Where Autor inspire innoati numbered 0,1,2,3,4,5,6,7,8; order 9,8,7,6,5,4,3,2,1,0) In this number of passes depends on number of digits i j 1 ae sorwd. é 4 of each pass, elements end fy x . 9 10 9, OUtbU Of this Pa ie Colle j 8 input ane ae for pass of Radix, ten’s qi cond P * dias ot yo Smen ary ot i ord of Radix SOM, 100 dais of i es anaso-on analysis osprey = C8) here> 4. = number of digits in the maxi ‘number in the given array, ane in = number of data elements in array. ow consider an aay having 7 clement (342, 896, 207, A= ; ix sort, last digits of elements are in first pass of Radi |= After completion © 396,207. + \60,350,101,342,4554 fort 4 asi wi _- Output of pass Lis wi we eee Se ass of RAGIX Sr, fast gi . "ES of they Poot oo . =e ~ After completion of second pass elements af 101,207,342,550,455,160,896. = Output of pas Is taken as input for pass Mt = ~ Inthind pass of Radix sort 100's digits of emesis am) (Mu, Data Structure and, i ve | Past = iter, digits in maximom number are 4. s0 we real 4 passes. Input Packets = In first pass of Radix sort last digits of elements ane AGE alee a re coi4 | 0014 Pass 1 047 | 0047 Packets wot} oo} 1 {2}s} als ‘8 |9]|| 0348 | 0348 = us 5901 5361 “ i 0514 | 0614 ou on ‘After completion of fourth pass elements are sor |_| set a a ‘After completion of first pass elements are: 5381, order using radix sort. 12, 8, 25, 614, 47 and 348, 66,2,98,225. Pass It = a |- Ee digits in maximum number are 3,50 we require o} 1 j/2/3| 4 |5/6|7| 8 [9 on ft Radi ardigit of. — In first pass of Radix sort last digit o a a pass git of a elements ae sorted wu | [is on on | or aa 47. a7 nut See “ 348 348 ae 2/3 si ei7ia ‘After completion of second pass elements are: 12 2 14,614,47,348,5381. 8 8 Pass 25 ry Input He tle hd 014 | 014 66 66 614 614 2 2 047 | 047 a i 48 48 a 5381 5381 225 After completion of third pass elements are: After completion of first pass elements are: 12. 4 14, 47, 348, 5381, 614. 25, 225, 66, 8, 98. Tech-Neo Publications... Where Authors inspire innovation competion of Second pas 795, 66> 98. 50 25 225 Thee To 098 | 98 ‘ale Jetion of third pass elements are: Alter comp! Spasses. ie igits of Chr puis aig i : | 1 } Hee, digits in maxis. 0S C jn eles | 02s 2» 0234 24 a ans 45 Ga 78 + i | 10 ! ae 360 C we. asa lal ot a ‘After completion of second pass elements. aq. = ws £42200,320, 729,8730,234,359,379,4580. [os s Pass ill ‘After completion of third pass elements are : Paka: oan] 304, 103, $4, 67, 49, 36,28, 25, 15,10, 7,3 wot oft] 2 [3 [4] 8 [el 7 [afal GO.5:725 Sort following elements by Radix sort {| | 42200 42200 algorithm 87.5, 2.54, 724, 3.59, ae 320 Marks) ‘| | 00729 7 Here, given elements are floating point first convert it | | 98722 oa into integer, for that multiply each element by 100. 00234 234 So lst is $730, 234, 729, 359, 4580, 379, 320, 42200 | | 00868 so Bae ky 00879 379 Digits in maximum number are 5, so we require 5 04580 4580 asses. In first pass of Radix sort last digits of elements are sorted. After completion of Third pass elements are: 42200,234,320,359,379,4580,729,8730. Pass IV a 234, 320 359 379 729 completion of foun fi ek 30.359. 379, 729, 4 3! 2200, 4 ments SH, Pas percompletion of Fth pass clemany mee rence between Quick sort . en and radix sont gam Compare quick sort ‘oily jiaing _| The working principle of Quick sortis as folows working pinile 1. Lowest index element sets pvtckenent | sons = MR of mx en 2. Partition the array around pivot clement such that each element in the right partion > pivot and ‘each element in the left partition < pivot. 3. Same procedure is applied recursively on let and right partition. Quick sort require sort. eng sy. 1. In Radix sort number of passes depends on number of digits in maximum number. In first pass of Radix sort unit digits of ‘numbers are sorted. ‘At the end of each pass numbers are collected from bucket 0 to 9, output of this Pass is taken as input for next Pass. {In second pass of Radix sort ten's digits ‘of aumbers ae sorted. i. ind pass of Radix sort 100's digits o Sin Pea sod and 008 2 4. of gts inthe maximam number ine tn deen 8 A ‘Soarching and. Data Structure and Analysis (MU= Sem. se 7g Techniques Syriabus Tople ANAS oF All Sortiny Radix Sort Law) a aa Syllabus Topic : Self Learning Topics = seanf("%e", Sal): Implementations of Different Sorting Techniques and Searching prin? Enter the number you want to sears: py) 5.8 IMPLEMENTATIONS OF DIFFERENT sean{('ed, search): SORTING TECHNIQUES AND 4 SEARCHING for @=0¢1< 514+) 2s 5.8.1 Implementation of Sequential / Linear Search { ‘Compare given x 2 e| clement with aray |" @ Program on linear search oll ne mee elements. Galéa1 wrike @ program to implement linear search for 40 elements in an array. { (10 Me print{("\n %d is present at location: Gd", search, i+ 1); Hinclude break; int main) ( , Upto end int 200}, search, im; ) clement not found, printf(\n Enter the size of array :"); it ==) Hin ee fens ( ) found print{("\n Enter %d numbers :", m); | found 4 * ait ney printf("wn ed is not present in array", for i= Oj < mit +) eae es Wee Aen of array : § numbers : 31.55 2 27 16 49 [oe cer the number fh recent at vant to: Yeeattae. te Search : 4g 1" ewe program first accepts a size of array lements from User. eaiiaay ‘Then accept a number which to be searched if given number is matched wit with array element then print number is found and its location. If none of element matches with element to search, then display message number is not found. 5.8.2 Implementation of Binary Search Program on binary Search #include int main) { 50) ink, lower, uppers mids ae print{("\n Enter size of 42 scanf("%d" 8) MN oer pa rakes Seeley Af given element eater than a“ tlnent tn cine ‘caching nerd ma ee if (arr mid} == search) If given elements equal to mid clement then print number is found, ‘rint('\n ed found at location: earch, mid +1) upper = mid -15 mid = ower + uppes?2s y ‘flower > upper) prin ed Not found in th int, sears setumn 0; enter size of array ¢7 enter 7 elenents : 5 37 21 vant to search + 7 Bae 1 || enter element you int mind) int ae{100}.nsemp.h rintf(Enter numberof elements you want tobe sor: scnf(Sdn); Accents Drint(Enter ed elements:"n);_ | user enter fi e WMments: 31 55 27 1648 ate ies wee cadt sta J forth =0h ae : 2 postion of eee } previous element int main) ae, and the position of | ¢ se temp mas ay a S element shifted int ar{100} i,j temps ; eee prini("Enter the numberof elements you want eee Accepts valve of am from user. ‘ rint{("Sorted elements are :"); 5 ae m ay for k=0; k inchade ina nein) t im ADO 0 nce iiShamieos print (Ve Merge seca"): einai" Enter the sine of areay A"); sand" Bes pe ("2 Eater elemeats of ray As"); pene ("ie Eats clement of ray B*); fer (i= 035 AB) 538) (vo ar) < for temp = AC Ag} = Ath Alt] = temps y » , fe(ke Osh eomasktt) { foe (I= b+ 131 <= mls 1+) t (BR) > BL) Son aay B sing selection son. k=o:i pint ("2 Array afer sorting 2); a ‘quicksor{int {10} inti); si int getMax(int are], int n) { int mx = arr{0); for (i Asi< mitt) if (ar{i] > ms) mx = artis return mx; + void eountSort(int are), int n, int exp) { int output{n};// output array int i, count{10} = {0}; {1/ Store count of oceurrences in count{} for (i= 0:1 < mit +) ccount{(arr{i]/ exp) 9 10]++5 for = 1; < 1051+) 0; exp *= 10) countSort(arr 1, exP)s ) ‘oid print (int arr}, int 2) { for (i= 0:1

You might also like