Advertisement
zhongnaomi

make 3 sorts list timeit

Feb 14th, 2019
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.21 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Thu Feb 14 14:39:07 2019
  4.  
  5. @author: Naomi Toshiba
  6. """
  7.  
  8. from timeit import timeit
  9. from random import randint
  10.  
  11.  
  12.  
  13.  
  14. ##################################################################
  15. # COPY AND PASTE YOUR bubble_sort AND merge_sort functions below #
  16.  
  17.  
  18. def tbubble_sort(seq):
  19.     """Inefficiently sort the mutable sequence (list) in place.
  20.       seq MUST BE A MUTABLE SEQUENCE.
  21.  
  22.       As with list.sort() and random.shuffle this does NOT return
  23.    """
  24.     changed = True
  25.     while changed:
  26.         changed = False
  27.         for i in range(len(seq) - 1):
  28.             if seq[i] > seq[i+1]:
  29.                 seq[i], seq[i+1] = seq[i+1], seq[i]
  30.                 changed = True
  31.     return seq
  32.            
  33.            
  34.  
  35. def merge1(list_a, list_b):
  36.     list_c = []
  37.     while len(list_a) > 0  and len(list_b) > 0:
  38.         if list_a[0] < list_b[0]:
  39.             list_c.append(list_a.pop(0))
  40.         else:
  41.             list_c.append(list_b.pop(0))
  42.     if list_a == []:
  43.         list_c += list_b
  44.     else:
  45.         list_c += list_a
  46.    
  47.     return list_c
  48.  
  49.  
  50. def merge_sort1(unsorted):
  51.     if len(unsorted) < 2:
  52.         return unsorted
  53.     else:
  54.         middle = len(unsorted) // 2
  55.         front = unsorted[:middle]
  56.         back = unsorted[middle:]
  57.        
  58.         front = merge_sort1(front)
  59.         back = merge_sort1(back)
  60.     return merge1(front, back)
  61.  
  62.  
  63.  
  64.  
  65. ##################################################################
  66.  
  67. def sort3list():
  68.     bslist =[]
  69.     mslist =[]
  70.     tislist =[]
  71.     m = 1
  72.     while m <=200:
  73.         #Generate a large (200 items) random list
  74.         list_to_sort = [randint(0,100000) for i in range(m)]
  75.         #Create anonymous functions to use with timeit, be sure to check these function names match your pasted ones
  76.         bs = lambda: tbubble_sort(list_to_sort)
  77.         ms = lambda: merge_sort1(list_to_sort)
  78.         tis = lambda: sorted(list_to_sort)
  79.         #time the functions for 100 runs each
  80.         bslist.append(timeit(bs, number =100))
  81.         mslist.append(timeit(ms, number = 100))
  82.         tislist.append(timeit(tis,number=100))
  83.         m +=1
  84.     return bslist,mslist,tislist
  85.        
  86.  
  87.  
  88.  
  89.  
  90. print(sort3list())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement