Advertisement
zhongnaomi

bubble sort, merge sort, timsort, timeit

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