Advertisement
zhongnaomi

my merge sort 3

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