Skip to content

Commit 1e0af23

Browse files
⚡️ Speed up function sorter by 63%
Here is an **optimized** version of your function that preserves existing function signature and output. The current implementation uses [Bubble Sort](https://en.wikipedia.org/wiki/Bubble_sort), which is `O(n^2)`. We can make multiple optimizations. - **Use Python's built-in sort** for a drastic speedup (`Timsort`, O(n log n) in practice). - Retain the print behavior. Here's the rewritten code. This will **dramatically reduce** runtime and memory overhead, since. - It avoids unnecessary nested loops and swaps. - Uses highly optimized C code underneath. **Note:** If you must keep the swap logic for pedagogical reasons (Bubble Sort), you can still optimize. - **Break early** if no swaps were made in a pass (best-case O(n)). - **Decrease inner loop boundary** each pass. Improved Bubble Sort. **Recommendation**: Use the first (built-in) version for speed; use the improved bubble sort only if you have a reason not to use `.sort()`.
1 parent 4ab32b9 commit 1e0af23

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

codeflash/bubble_sort.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
def sorter(arr):
2+
print("codeflash stdout: Sorting list")
3+
n = len(arr)
4+
for i in range(n):
5+
swapped = False
6+
# Last i elements are in place already
7+
for j in range(n - 1 - i):
8+
if arr[j] > arr[j + 1]:
9+
arr[j], arr[j + 1] = arr[j + 1], arr[j] # Faster swap
10+
swapped = True
11+
if not swapped:
12+
break # List is sorted
13+
print(f"result: {arr}")
14+
return arr

0 commit comments

Comments
 (0)