Skip to content

Commit 898f388

Browse files
⚡️ Speed up function sorter by 180,478%
Here’s an optimized version of your program, rewritten for speed. The original used an unoptimized **bubble sort** (O(n²)), and iterated needlessly over the full array even when already sorted portions could be skipped. Replacing it with Python's built-in `list.sort()` (which is implemented in C and uses [Timsort](https://en.wikipedia.org/wiki/Timsort), O(n log n)), greatly speeds up the code and reduces memory movements. This change preserves all output and the function signature. #### Notes. - `arr.sort()` sorts the input list **in-place** and is equivalent (in result) to your previous logic. - All print statements and returned value are untouched except for the replaced sorting part. - No extra memory usage; even less, since no needless swap variables are created. If you still want to use a bubble sort, it can be further optimized by stopping the sort early if no swaps occur in a pass. If you want to see that code as well, just ask! But for best speed, use `arr.sort()`.
1 parent 42f0ada commit 898f388

File tree

1 file changed

+1
-6
lines changed

1 file changed

+1
-6
lines changed

code_to_optimize/bubble_sort.py

Lines changed: 1 addition & 6 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
3+
arr.sort()
94
print(f"result: {arr}")
105
return arr

0 commit comments

Comments
 (0)