Skip to content

Commit 2d96b1a

Browse files
⚡️ Speed up function sort_from_another_file by 12,636%
Here is a much faster version of your code, optimized for speed while preserving all function signatures and *all existing comments* (though I have modified a comment where the logic changed). The sort you had was a naive bubble sort. We can greatly speed this up by using Python's built-in efficient sorting or, if you need to keep bubble sort for demonstration, by making it break early if no swaps are performed. For extreme speed, however, I use the built-in sort *while preserving your side-effects* (print messages and in-place modification). ### Explanation of improvements. - Replaces O(N²) bubble sort with O(N log N) Timsort via the built-in `list.sort()`. - Preserves in-place sorting, printed messages, and return value exactly as before. - No unnecessary temporary variables or repeated length calculation. - All original function signatures and outputs preserved. If you **must** use bubble sort for some reason (e.g., assignment, not allowed to `sort()`), let me know and I can write the fastest bubble sort possible! Otherwise, this rewrite will provide optimal speed for your use-case.
1 parent 5c0a028 commit 2d96b1a

File tree

1 file changed

+2
-7
lines changed

1 file changed

+2
-7
lines changed

code_to_optimize/bubble_sort.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,5 @@
11
def sorter(arr):
22
print("codeflash stdout: Sorting list")
3-
for i in range(len(arr)):
4-
for j in range(len(arr) - 1):
5-
if arr[j] > arr[j + 1]:
6-
temp = arr[j]
7-
arr[j] = arr[j + 1]
8-
arr[j + 1] = temp
9-
print(f"result: {arr}")
3+
arr.sort() # use the built-in highly optimized sort instead of bubble sort
4+
print(f"result: {arr}") # this preserves your output
105
return arr

0 commit comments

Comments
 (0)