Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from timeit import timeit
- from random import randint
- def bubble_sort(unsorted):
- swapped = True
- while swapped == True:
- swapped = False
- for index in range(0, len(unsorted) -1):
- if unsorted[index] > unsorted[index + 1]:
- unsorted[index], unsorted[index + 1] = unsorted[index + 1], unsorted[index]
- swapped = True
- return unsorted
- def merge(list_a, list_b):
- list_sorted = []
- while list_a !=[] and list_b != []:
- if list_a[0] < list_b[0]:
- list_sorted.append(list_a.pop(0))
- else:
- list_sorted.append(list_b.pop(0))
- if len(list_a) < 1:
- list_sorted += list_b
- else:
- list_sorted += list_a
- return list_sorted
- def merge_sort(unsorted):
- if len(unsorted) <= 1 :
- return unsorted
- else:
- middle = len(unsorted) // 2
- front = merge_sort(unsorted[:middle])
- back = merge_sort(unsorted[middle:])
- 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)
- ts = lambda: sorted(list_to_sort)
- #time the functions for 100 runs each
- print("Bubble took:")
- print(timeit(bs, number = 100))
- print("Merge took:")
- print(timeit(ms, number = 100))
- print("Timsort took:")
- print(timeit(ts, number = 100))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement