Skip to content

Instantly share code, notes, and snippets.

@Kush1101
Last active September 1, 2020 07:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kush1101/e37454fcb6954c6bbfafd34393d339ba to your computer and use it in GitHub Desktop.
Save Kush1101/e37454fcb6954c6bbfafd34393d339ba to your computer and use it in GitHub Desktop.
def bubble_sort(arr):
for i in range(len(arr)):
for j in range(0, len(arr) - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
def make_random_array():
from random import randint
return [randint(-100, 100) for i in range(20)]
test_array = make_random_array()
'''
Since we want to make sure that we test our functions on the same array, we are declaring an array
here and will later call it in compare_functions().
'''
def compare_functions():
import timeit
setup_code1 = """
from __main__ import bubble_sort
from __main__ import test_array
"""
setup_code2 = """
from __main__ import test_array
"""
stmt_code1 = "bubble_sort(test_array)"
stmt_code2 = "sorted(test_array)"
times1 = timeit.repeat(stmt=stmt_code1, setup=setup_code1, number=10000, repeat=5)
times2 = timeit.repeat(stmt=stmt_code2, setup=setup_code2, number=10000, repeat=5)
print(f"Time taken by bubble sort is {min(times1)}")
print(f"Time taken by built in sort is {min(times2)}")
if __name__ == "__main__":
compare_functions()
"""
Time taken by bubble sort is 0.2646727000001192
Time taken by built in sort is 0.0031973000000107277
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment