Advertisement
farrismp

Sort tests

May 6th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. from 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 = merge_sort(unsorted[:middle])
  33. back = merge_sort(unsorted[middle:])
  34.  
  35. return merge(front, back)
  36.  
  37. #Generate a large (1000 items) random list
  38. list_to_sort = [randint(0,100000) for i in range(1000)]
  39.  
  40. #Create anonymous functions to use with timeit, be sure to check these function names match your pasted ones
  41. bs = lambda: bubble_sort(list_to_sort)
  42. ms = lambda: merge_sort(list_to_sort)
  43. ts = lambda: sorted(list_to_sort)
  44.  
  45. #time the functions for 100 runs each
  46.  
  47. print("Bubble took:")
  48. print(timeit(bs, number = 100))
  49.  
  50. print("Merge took:")
  51. print(timeit(ms, number = 100))
  52.  
  53. print("Timsort took:")
  54. print(timeit(ts, number = 100))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement