Skip to content

Commit b37d3bb

Browse files
authored
Update bubble_sort.py
1 parent 525d161 commit b37d3bb

File tree

1 file changed

+10
-13
lines changed

1 file changed

+10
-13
lines changed

Diff for: sorts/bubble_sort.py

+10-13
Original file line numberDiff line numberDiff line change
@@ -106,28 +106,25 @@ def bubble_sort_recursive(collection: list[Any]) -> list[Any]:
106106

107107
if __name__ == "__main__":
108108
import doctest
109+
from random import sample
109110
from timeit import timeit
110111

111112
doctest.testmod()
112113

113-
user_input = input("Enter numbers separated by a comma:").strip()
114-
unsorted = [
115-
int(item) if isinstance(item, int) else float(item)
116-
for item in user_input.split(",")
117-
]
118-
119-
num_runs = 1000
114+
# Benchmark: Iterative seems slightly faster than recursive.
115+
num_runs = 10_000
116+
unsorted = sample(range(-50, 50), 100)
120117
timer_iterative = timeit(
121118
"bubble_sort_iterative(unsorted[:])", globals=globals(), number=num_runs
122119
)
123-
timer_recursive = timeit(
124-
"bubble_sort_recursive(unsorted[:])", globals=globals(), number=num_runs
125-
)
126-
127120
print("\nIterative bubble sort:")
128121
print(*bubble_sort_iterative(unsorted), sep=",")
129-
print(f"Processing time (iterative): {timer_iterative:.5f} s for {num_runs} runs")
122+
print(f"Processing time (iterative): {timer_iterative:.5f}s for {num_runs:,} runs")
130123

124+
unsorted = sample(range(-50, 50), 100)
125+
timer_recursive = timeit(
126+
"bubble_sort_recursive(unsorted[:])", globals=globals(), number=num_runs
127+
)
131128
print("\nRecursive bubble sort:")
132129
print(*bubble_sort_recursive(unsorted), sep=",")
133-
print(f"Processing time (recursive): {timer_recursive:.5f} s for {num_runs} runs")
130+
print(f"Processing time (recursive): {timer_recursive:.5f}s for {num_runs:,} runs")

0 commit comments

Comments
 (0)