Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from timeit import timeit
- from random import randint
- ##################################################################
- # COPY AND PASTE YOUR bubble_sort AND merge_sort functions below #
- def bubble_sort(sorted):
- n = len(sorted)
- while (n >= 1 ) :
- newn = 0
- for i in range(1, len(sorted)):
- if sorted[i-1] > sorted[i]:
- sorted[i-1], sorted[i] = sorted[i], sorted[i-1]
- newn = i
- n = newn
- return sorted
- def merge(list_a, list_b):
- list_c = []
- while len(list_a) > 0 and len(list_b) > 0:
- if list_a[0] < list_b[0]:
- list_c.append(list_a.pop(0))
- else:
- list_c.append(list_b.pop(0))
- if list_a == []:
- list_c += list_b
- else:
- list_c += list_a
- return list_c
- def merge_sort(unsorted):
- if len(unsorted) < 2:
- return unsorted
- else:
- middle = len(unsorted) // 2
- front = unsorted[:middle]
- back = unsorted[middle:]
- front = merge_sort(front)
- back = merge_sort(back)
- return merge(front, back)
- ##################################################################
- #Generate a large (1000 items) random list
- list_to_sort = [randint(0,100000) for i in range(1000)]
- #Create anonymous functions to use with timeit, be sure to check these function names match your pasted ones
- bs = lambda: bubble_sort(list_to_sort)
- ms = lambda: merge_sort(list_to_sort)
- #time the functions for 100 runs each
- print("Merge took:")
- print(timeit(ms, number = 100))
- print("Bubble took:")
- print(timeit(bs, number = 100))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement