Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from random import randint
- from time import time
- import sys
- # RUN CODE FROM CONSOLE LIKE THIS:
- # python sorting.py {int for list length} {sorted | unsorted}
- # Example: sorting.py 500 unsorted
- count = int(sys.argv[1])
- unsorted1 = unsorted2 = [randint(1, 99) for _ in range(count)][:]
- print("\nCREATED LISTS\n")
- if sys.argv[2] == 'sorted':
- unsorted1.sort()
- unsorted2.sort()
- def my_bubble_sort(n):
- switched = True
- while switched:
- switched = False
- for i in range(1, len(n)):
- if n[i] < n[i - 1]:
- switched = True
- n[i - 1], n[i] = n[i], n[i - 1]
- return n
- def some_other_bubble_sort(n):
- for i in range(len(n) - 1):
- for j in range(len(n) - 1 - i):
- if n[j] > n[j + 1]:
- n[j], n[j + 1] = n[j + 1], n[j]
- return n
- start = time()
- my_bubble_sort(unsorted1)
- duration1 = time() - start
- print(f"My own bubble sort took {duration1} seconds to finish.\n")
- start = time()
- some_other_bubble_sort(unsorted2)
- duration2 = time() - start
- print(f"That other bubble sort took {duration2} seconds to finish.\n")
- if duration1 < duration2:
- print(f"My own bubble sort was faster and took only {(duration1/duration2):.2%} of the time.\n")
- else:
- 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