Advertisement
zhongnaomi

my merge sort 2

Feb 13th, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.90 KB | None | 0 0
  1. from random import randint
  2.  
  3. list_to_sort = [randint(1,100) for i in range(50)]
  4. print(list_to_sort)
  5. def merge(list_a, list_b):
  6.     list_c = []
  7.     while len(list_a) > 0  and len(list_b) > 0:
  8.         if list_a[0] < list_b[0]:
  9.             list_c.append(list_a.pop(0))
  10.         else:
  11.             list_c.append(list_b.pop(0))
  12.     if list_a == []:
  13.         list_c += list_b
  14.     else:
  15.         list_c += list_a
  16.     print("merged list is", list_c)
  17.     return list_c
  18.  
  19.  
  20. def merge_sort(unsorted):
  21.     if len(unsorted) <=1:
  22.         return unsorted
  23.     front =[]
  24.     back =[]
  25.    
  26.     for i,x in enumerate(unsorted,start=0):
  27.        
  28.         if i < len(unsorted)/2:
  29.             front.append(x)
  30.         else:
  31.             back.append(x)
  32.            
  33.     print("splits are", front, back)
  34.     front = merge_sort(front)
  35.     back = merge_sort(back)
  36.     return merge(front, back)
  37.  
  38. merge_sort(list_to_sort)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement