teromakotero

Tim sort

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