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 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 bubble_sort(unsorted):
- #print (my_list)
- # create a duplicate of the original list
- my_list_duplicate = list_to_sort
- # intialise a variable called swapped to true. This will be used to track if changes are made in a pass
- swapped = True
- # repeat the following as long as swapped is true
- while swapped == True:
- # set swapped to false
- swapped = False
- # for each item in the list
- for x in range (len(my_list_duplicate)-1):
- # if the current item is greater than the next item
- if my_list_duplicate[x]>my_list_duplicate[x+1]:
- # set the current item of the array as current_item
- current_item = my_list_duplicate[x]
- # set the next item in the array as next_item
- next_item = my_list_duplicate[x+1]
- # change the current item to the one after it
- my_list_duplicate[x] = next_item
- # and the next position to the current one. In other words, swap them around
- my_list_duplicate[x+1] = current_item
- # set swapped to true
- swapped = True
- # if no swaps were made
- if swapped == False:
- # return the new list
- return my_list_duplicate
- def time_sort(unsorted):
- sorted_list = sorted(unsorted)
- return sorted_list
- #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: time_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))
- print("Timesort took:")
- print(timeit(ts, number = 100))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement