Advertisement
kevinbocky

timed_sorting_method.py

Jan 28th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. #time sorting methods
  2. from timeit import timeit
  3. import random
  4. numbers = [random.randint(0,10000) for i in range(1000)]
  5.  
  6. bs = lambda: bubblesort(numbers)
  7. ms = lambda: merge_sort(numbers)
  8. ts = lambda: sorted(numbers) #sorted = Timsort function built-in to Python
  9.  
  10. def bubblesort(list): #define the bubblesort function
  11. sorted1 = list[:] #copy of old list(numbers)
  12. sort = True
  13. while sort == True: #while loop start, then sets sort to False, if it has to perform action, sets sort back to True
  14. sort = False #if it has to perform no action, sort stays False ,while loop ends
  15. for i in range(len(sorted1) - 1):
  16. if sorted1[i] > sorted1[i+1]:
  17. sorted1[i], sorted1[i+1] = sorted1[i+1], sorted1[i]
  18. sort = True #turns sort back to True if action performed
  19.  
  20. print(sorted1)
  21.  
  22. bubblesort(numbers)
  23.  
  24.  
  25. def merge(list1, list2): #merge function works with mergesort
  26. list3 = []
  27. while len(list1) > 0 and len(list2) > 0:
  28. if list1[0] < list2[0]:
  29. list3.append(list1.pop(0))
  30. else:
  31. list3.append(list2.pop(0))
  32. if list1 == []:
  33. list3 += list2
  34. else:
  35. list3 += list1
  36. print("merged list is", list3)
  37. return list3
  38.  
  39.  
  40.  
  41.  
  42. def merge_sort(unsorted): #mergesort function works with merge
  43. if len(unsorted) < 2:
  44. return unsorted
  45. else:
  46. middle = len(unsorted) // 2
  47. front = unsorted[:middle]
  48. back = unsorted[middle:]
  49. print("splits are", front, back)
  50. front = merge_sort(front)
  51. back = merge_sort(back)
  52. return merge(front, back)
  53.  
  54.  
  55. print("Merge took:")
  56. print(timeit(ms, number = 100)) #timeit to compare completion times between sorting methods
  57.  
  58. print("Bubble took:")
  59. print(timeit(bs, number = 100))
  60.  
  61. print("Timsort took:")
  62. print(timeit(ts, number = 100))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement