Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from timeit import timeit
- from random import randint
- def swapme(my_list):
- for i in range(len(my_list)-1):
- if my_list[i+1]< my_list[i]:
- temporary=my_list[i+1]
- my_list[i+1]=my_list[i]
- my_list[i]=temporary
- return my_list
- def bubble_sorted(my_list):
- sorted = my_list[:]
- toSort = []
- toSort.append(sorted)
- swapped=True
- while swapped==True:
- swapme(my_list)
- swapped=my_list[:]
- toSort.append(swapped)
- swapped=True
- if toSort[-1]==toSort[-2]:
- swapped=False
- return toSort
- 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
- #***************************print("merged list is", list_c)
- 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 timSort(unsorted):
- return(sorted(unsorted))
- #Generate a large (1000 items) random list
- list_to_sort = [randint(0,100000) for i in range(2500)]
- #Create anonymous functions to use with timeit, be sure to check these function names match your pasted ones
- bs = lambda: bubble_sorted(list_to_sort)
- ms = lambda: merge_sort(list_to_sort)
- ts = lambda: timSort(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