Advertisement
Guest User

Untitled

a guest
Feb 18th, 2020
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 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.  
  9. ### BUBBLE Sort
  10.  
  11. def bubble_sort(unsorted):
  12.  
  13. ### MAKE COPY OF ORIGINAL LIST ###
  14. original_list = list_to_sort[:]
  15.  
  16. swapped = True
  17.  
  18. while swapped:
  19. swapped = False
  20. for i in range(len(unsorted) - 1):
  21. if unsorted[i] > unsorted[i+1]:
  22. unsorted[i], unsorted[i+1] = unsorted[i+1], unsorted[i]
  23. swapped = True
  24.  
  25.  
  26.  
  27. ### MERGE Sort
  28.  
  29. def merge(list_a, list_b):
  30. list_sorted = []
  31. while list_a != [] and list_b != []:
  32. if list_a[0] < list_b[0]:
  33. list_sorted.append(list_a.pop(0))
  34. else:
  35. list_sorted.append(list_b.pop(0))
  36. if len(list_a) < 1:
  37. list_sorted += list_b
  38. else:
  39. list_sorted += list_a
  40. return list_sorted
  41.  
  42.  
  43. def merge_sort(unsorted):
  44. if len(unsorted) <= 1:
  45. return unsorted
  46. else:
  47. middle = len(unsorted) // 2 # rounding down if the list has an odd number of items
  48. front = unsorted[:middle]
  49. back = unsorted[middle:]
  50. front = merge_sort(front)
  51. back = merge_sort(back)
  52. return merge(front, back)
  53.  
  54.  
  55. #Generate a large (10 items) random list
  56. list_to_sort = [randint(0,100000) for i in range(1000)]
  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.  
  62. #time the functions for 100 runs each
  63.  
  64. print("Merge took:")
  65. print(timeit(ms, number = 100))
  66.  
  67. print("Bubble took:")
  68. print(timeit(bs, number = 100))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement