Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from timeit import timeit
- from random import randint
- '''
- BUBBLE SORT START
- '''
- #This program takes an unsorted list and sorts it, then stores the results in copy_list
- #my_list becomes filled with a collection of random integers, the amount of which is specified the user;
- #individual list items could be specified by replacing randint with another input block
- my_list = []
- def bubble_sort(unsorted):
- #iterates through original list and copies each item into copy_list
- copy_list = unsorted[:]
- #sets loop condition so loop will proceed
- swapped = True
- while swapped == True:
- #sets loop to terminate after having iterated and swapped all necessary items in copy list
- swapped = False
- for num in range(len(copy_list)-1):
- #swaps item order if a preceding number is greater than that which follows
- if copy_list[num] > copy_list[num + 1]:
- copy_list[num], copy_list[num + 1] = copy_list[num + 1], copy_list[num]
- #sets loop to continue until numbers are ordered
- swapped = True
- return copy_list
- '''
- BUBBLE SORT END
- '''
- '''
- MERGE SORT START
- '''
- #Sorting algoirthm which compares two SORTED lists and merges into a single sorted list
- 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
- #Splitting alogorithm whic breaks unsorted lists in half until individual 'sorted' lists produced, which can be fed into merge function
- def merge_sort(unsorted):
- if len(unsorted) <= 1:
- return unsorted
- else:
- middle = len(unsorted) // 2
- front = unsorted[:middle]
- back = unsorted[middle:]
- front = merge_sort(unsorted[:middle])
- back = merge_sort(unsorted[middle:])
- return merge(front, back)
- '''
- MERGE SORT END
- '''
- '''
- TIMER PROGRAM START
- '''
- #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, and include Timsort algorithm for comparison
- 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))
- '''
- TIMER PROGRAM END
- '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement