@@ -139,8 +139,13 @@ def setAlgo(self, key=False):
139139 self .algorithms = {
140140 "Bubble Sort" : self .bubbleSort ,
141141 "Insertion Sort" : self .insertionSort ,
142+ "Merge Sort" : self .mergeSort ,
143+ }
144+ key_to_name = {
145+ pygame .K_b : "Bubble Sort" ,
146+ pygame .K_i : "Insertion Sort" ,
147+ pygame .K_m : "Merge Sort" ,
142148 }
143- key_to_name = {pygame .K_b : "Bubble Sort" , pygame .K_i : "Insertion Sort" }
144149 self .algo_keys = key_to_name .keys ()
145150 if not key :
146151 key = list (self .algo_keys )[0 ]
@@ -164,7 +169,6 @@ def bubbleSort(self):
164169 num1 < num2 and not self .ascending
165170 ):
166171 self .list [j ], self .list [j + 1 ] = self .list [j + 1 ], self .list [j ]
167- self .drawList (clear_bg = True )
168172 yield True
169173
170174 def insertionSort (self ):
@@ -179,10 +183,48 @@ def insertionSort(self):
179183 break
180184 self .list [i ], self .list [i - 1 ] = self .list [i - 1 ], current
181185 i -= 1
182- self .drawList (clear_bg = True )
183186 yield True
184187
185- # TODO add Merge Sort
188+ def mergeSort (self , start = 0 , end = False ):
189+ if not end :
190+ end = self .len_list
191+ if end - start > 1 :
192+ middle = (start + end ) // 2
193+
194+ yield from self .mergeSort (start , middle )
195+ yield from self .mergeSort (middle , end )
196+ left = self .list [start :middle ]
197+ right = self .list [middle :end ]
198+
199+ a = 0
200+ b = 0
201+ c = start
202+
203+ while a < len (left ) and b < len (right ):
204+ if left [a ] < right [b ]:
205+ self .list [c ] = left [a ]
206+ a += 1
207+ else :
208+ self .list [c ] = right [b ]
209+ b += 1
210+ c += 1
211+ yield True
212+
213+ while a < len (left ):
214+ self .list [c ] = left [a ]
215+ a += 1
216+ c += 1
217+ yield True
218+
219+ while b < len (right ):
220+ self .list [c ] = right [b ]
221+ b += 1
222+ c += 1
223+ yield True
224+
225+ yield True
226+
227+ # TODO add Merge Sort descending functionality
186228 # TODO add Heap Sort
187229 # TODO add Quick Sort
188230
@@ -197,8 +239,8 @@ def main(size=600):
197239 try :
198240 next (screen .getGen ())
199241 except StopIteration :
200- screen .drawList (clear_bg = True )
201242 sorting = False
243+ screen .drawList (clear_bg = True )
202244
203245 for event in pygame .event .get ():
204246 if event .type == pygame .QUIT :
0 commit comments