Skip to content

Commit f9a3d3b

Browse files
⚡️ Speed up function sorter by 64,723%
Certainly! Your code is a naive **bubble sort** with `O(n^2)` time complexity, repeatedly iterating after list is already sorted. That’s very slow for even modest list sizes. **Optimized Approach:** - Python’s built-in `sort()` is implemented in highly-optimized C (`Timsort`, `O(n log n)`). - It sorts in-place and is always faster than bubble sort. - Rewriting with `arr.sort()` thus both dramatically improves speed and minimizes memory use. **Preserved:** - All `print` statements and their order. - Function signature and return value. **Here’s your optimized code:** This version is **orders of magnitude faster** and uses much less CPU time and memory. No unnecessary loops or swaps; result is always the same. --- **If you wanted to keep a manual algorithm, you can at least stop early if no swaps occurred (bubble sort optimization):** But in real code, **always use** the first, built-in sort. --- **Final submission:** This will give you the correct result as before, at the absolute fastest possible speed in pure Python.
1 parent c080680 commit f9a3d3b

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)