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(unclassified):
- changed = True
- while changed == True:
- changed = False
- for item in range(len(unclassified) - 1):
- if unclassified[item] > unclassified[item+1]:
- unclassified[item], unclassified[item+1] = unclassified[item+1], unclassified[item] # Swapping list items around
- changed = True
- return unclassified
- 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)
- def mergeSort(alist):
- if len(alist)>1:
- mid = len(alist)//2
- lefthalf = alist[:mid]
- righthalf = alist[mid:]
- #recursion
- mergeSort(lefthalf)
- mergeSort(righthalf)
- i=0
- j=0
- k=0
- while i < len(lefthalf) and j < len(righthalf):
- if lefthalf[i] < righthalf[j]:
- alist[k]=lefthalf[i]
- i=i+1
- else:
- alist[k]=righthalf[j]
- j=j+1
- k=k+1
- while i < len(lefthalf):
- alist[k]=lefthalf[i]
- i=i+1
- k=k+1
- while j < len(righthalf):
- alist[k]=righthalf[j]
- j=j+1
- k=k+1
- #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)
- ps = lambda: mergeSort(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("Other Merge took:")
- print(timeit(ps, number = 100))
Add Comment
Please, Sign In to add comment