Advertisement
xavicano

Untitled

Aug 19th, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.96 KB | None | 0 0
  1. from timeit import timeit
  2. from random import randint
  3.  
  4. ##################################################################
  5. # COPY AND PASTE YOUR bubble_sort AND merge_sort functions below #
  6. ##################################################################
  7.  
  8.  
  9. def merge(list_a, list_b):
  10.     list_c = []
  11.     while len(list_a) > 0  and len(list_b) > 0:
  12.         if list_a[0] < list_b[0]:
  13.             list_c.append(list_a.pop(0))
  14.         else:
  15.             list_c.append(list_b.pop(0))
  16.     if list_a == []:
  17.         list_c += list_b
  18.     else:
  19.         list_c += list_a
  20. #   print("merged list is", list_c)
  21.     return list_c
  22.  
  23.  
  24. def merge_sort(unsorted):
  25.     if len(unsorted) < 2:
  26.         return unsorted
  27.     else:
  28.         middle = len(unsorted) // 2
  29.         front = unsorted[:middle]
  30.         back = unsorted[middle:]
  31. #       print("splits are", front, back)
  32.         front = merge_sort(front)
  33.         back = merge_sort(back)
  34.     return merge(front, back)
  35.  
  36.  
  37. def bubble_sort(unsorted):
  38.     swapped = True
  39.     while swapped:
  40.         swapped = False
  41.         for i in range(len(unsorted)-1):
  42.             if unsorted[i] > unsorted[i+1]:
  43.                 temp=unsorted[i]
  44.                 unsorted[i]=unsorted[i+1]
  45.                 unsorted[i+1]=temp
  46.                 swapped = True
  47.     return unsorted        
  48.  
  49. #Generate a large (1000 items) random list
  50. for i in range(10):
  51.     list_to_sort = [randint(0,100000) for i in range(50000)]
  52.     #list_to_sort=[]
  53.     #for i in range(50):
  54.         #list_to_sort.append(50)
  55.  
  56.     unsorted = list_to_sort[:]
  57.     #print("Buble list = ", list_to_sort)
  58.  
  59.     #Create anonymous functions to use with timeit, be sure to check these function names match your pasted ones
  60.     bs = lambda: bubble_sort(list_to_sort)
  61.     ms = lambda: merge_sort(list_to_sort)
  62.     ts = lambda: sorted(list_to_sort)
  63.  
  64.     #time the functions for 100 runs each
  65.     merge_var=timeit(ms, number = 100)
  66.     print("Merge took: ",merge_var)
  67.     bubble_var=timeit(bs, number = 100)
  68.     print("Bubble took: ",bubble_var)
  69.     ts_var=timeit(ts, number = 100)
  70.     print("TimSort took: ",ts_var)
  71.     #if merge_var<bubble_var:
  72.         #print("Merge is better ")
  73.     #else:
  74.         #print("Bubble better")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement