Advertisement
Guest User

Bubble Sort comparison

a guest
Jun 23rd, 2018
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. from random import randint
  2. from time import time
  3. import sys
  4.  
  5.  
  6. # RUN CODE FROM CONSOLE LIKE THIS:
  7. # python sorting.py {int for list length} {sorted | unsorted}
  8. # Example: sorting.py 500 unsorted
  9.  
  10.  
  11. count = int(sys.argv[1])
  12.  
  13. unsorted1 = unsorted2 = [randint(1, 99) for _ in range(count)][:]
  14.  
  15. print("\nCREATED LISTS\n")
  16.  
  17. if sys.argv[2] == 'sorted':
  18.     unsorted1.sort()
  19.     unsorted2.sort()
  20.  
  21. def my_bubble_sort(n):
  22.     switched = True
  23.     while switched:
  24.         switched = False
  25.         for i in range(1, len(n)):
  26.             if n[i] < n[i - 1]:
  27.                 switched = True
  28.                 n[i - 1], n[i] = n[i], n[i - 1]
  29.     return n
  30.  
  31.  
  32. def some_other_bubble_sort(n):
  33.     for i in range(len(n) - 1):
  34.         for j in range(len(n) - 1 - i):
  35.             if n[j] > n[j + 1]:
  36.                 n[j], n[j + 1] = n[j + 1], n[j]
  37.     return n
  38.  
  39.  
  40. start = time()
  41. my_bubble_sort(unsorted1)
  42. duration1 = time() - start
  43.  
  44. print(f"My own bubble sort took {duration1} seconds to finish.\n")
  45.  
  46. start = time()
  47. some_other_bubble_sort(unsorted2)
  48. duration2 = time() - start
  49.  
  50. print(f"That other bubble sort took {duration2} seconds to finish.\n")
  51.  
  52. if duration1 < duration2:
  53.     print(f"My own bubble sort was faster and took only {(duration1/duration2):.2%} of the time.\n")
  54. else:
  55.     print(f"The other bubble sort was faster and took only {(duration2/duration1):.2%} of the time.\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement