Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #time sorting methods
- from timeit import timeit
- import random
- numbers = [random.randint(0,10000) for i in range(1000)]
- bs = lambda: bubblesort(numbers)
- ms = lambda: merge_sort(numbers)
- ts = lambda: sorted(numbers) #sorted = Timsort function built-in to Python
- def bubblesort(list): #define the bubblesort function
- sorted1 = list[:] #copy of old list(numbers)
- sort = True
- while sort == True: #while loop start, then sets sort to False, if it has to perform action, sets sort back to True
- sort = False #if it has to perform no action, sort stays False ,while loop ends
- for i in range(len(sorted1) - 1):
- if sorted1[i] > sorted1[i+1]:
- sorted1[i], sorted1[i+1] = sorted1[i+1], sorted1[i]
- sort = True #turns sort back to True if action performed
- print(sorted1)
- bubblesort(numbers)
- def merge(list1, list2): #merge function works with mergesort
- list3 = []
- while len(list1) > 0 and len(list2) > 0:
- if list1[0] < list2[0]:
- list3.append(list1.pop(0))
- else:
- list3.append(list2.pop(0))
- if list1 == []:
- list3 += list2
- else:
- list3 += list1
- print("merged list is", list3)
- return list3
- def merge_sort(unsorted): #mergesort function works with merge
- 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)
- print("Merge took:")
- print(timeit(ms, number = 100)) #timeit to compare completion times between sorting methods
- 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