Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #-------------------------------------------------------------------------------
- # Name: module2
- # Purpose:
- #
- # Author: DGarey
- #
- # Created: 12/01/2020
- # Copyright: (c) DGarey 2020
- # Licence: <your licence>
- #-------------------------------------------------------------------------------
- from timeit import timeit
- from random import randint
- ##################################################################
- # COPY AND PASTE YOUR bubble_sort AND merge_sort functions below #
- ##################################################################
- 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:]
- #print("splits are ", front, back)
- front = merge_sort(front)
- back = merge_sort(back)
- return merge(front, back)
- def bubble_sort(unsorted):
- sorted = unsorted[:]
- change = True
- while change:
- change = False
- for i in range(len(sorted) - 1):
- if sorted[i] > sorted[i+1]:
- sorted[i],sorted[i+1] = sorted[i+1], sorted[i] #Swap the item listchange
- change = True
- return sorted
- #Generate a large (1000 items) random list
- list_to_sort = [randint(0,100000) for i in range(10)]
- # Timsort program
- from timeit import timeit
- from random import randint
- import random
- my_list = [randint(0,100000) for i in range(1000)]
- print("Timsort took:")
- print(timeit(ts, number = 100))
- #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("Merge took:")
- print(timeit(ms, number = 100))
- print("Bubble took:")
- print(timeit(bs, number = 100))
- print("Timsort took:")
- print(timeit(ts, number = 100))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement