Advertisement
scarygarey

timsort_bubble_merge

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