Advertisement
Mori007

CompareSortedmodul

May 12th, 2019
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. rom timeit import timeit
  2. from random import randint
  3.  
  4. def bubble_sort(unsorted):
  5. swapped = True
  6. while swapped == True:
  7. swapped = False
  8. for index in range(0, len(unsorted) -1):
  9. if unsorted[index] > unsorted[index + 1]:
  10. unsorted[index], unsorted[index + 1] = unsorted[index + 1], unsorted[index]
  11. swapped = True
  12. return unsorted
  13.  
  14. def merge(list_a, list_b):
  15. list_sorted = []
  16. while list_a !=[] and list_b != []:
  17. if list_a[0] < list_b[0]:
  18. list_sorted.append(list_a.pop(0))
  19. else:
  20. list_sorted.append(list_b.pop(0))
  21. if len(list_a) < 1:
  22. list_sorted += list_b
  23. else:
  24. list_sorted += list_a
  25. return list_sorted
  26.  
  27. def merge_sort(unsorted):
  28. if len(unsorted) <= 1 :
  29. return unsorted
  30. else:
  31. middle = len(unsorted) // 2
  32. front = unsorted[:middle]
  33. back = unsorted[middle:]
  34. return merge(front, back)
  35.  
  36. #Generate a large (1000 items) random list
  37. list_to_sort = [randint(0,100000) for i in range(1000)]
  38.  
  39. #Create anonymous functions to use with timeit, be sure to check these function names match your pasted ones
  40. bs = lambda: bubble_sort(list_to_sort)
  41. ms = lambda: merge_sort(list_to_sort)
  42. ts = lambda: sorted(list_to_sort)
  43.  
  44. #time the functions for 100 runs each
  45.  
  46. print("Merge result:")
  47. print(timeit(ms, number = 100))
  48.  
  49. print("Bubble result:")
  50. print(timeit(bs, number = 100))
  51.  
  52. print("Tim result:")
  53. print(timeit(ms, number = 100))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement