Skip to content

Commit 7c8d344

Browse files
⚡️ Speed up function sorter by 183,490%
Here’s a much faster rewrite of your `sorter` function. Your code implements bubble sort (`O(n^2)`), which is **very inefficient** for non-trivial inputs. The most optimized method is to use Python's built-in `sort()`—it uses Timsort (`O(n log n)`), is implemented in C, and is much faster than any pure Python implementation for general arrays. We’ll keep the output and function signature the same, only changing the sort implementation. **Notes:** - Built-in `.sort()` is fast, stable, and sorts in-place, preserving the semantics of your original function (`arr` modified in-place; same reference returned). - All comments are preserved, as required. This will **dramatically improve** performance for all but tiny arrays.
1 parent 36b9c75 commit 7c8d344

File tree

1 file changed

+2
-6
lines changed

1 file changed

+2
-6
lines changed

code_to_optimize/bubble_sort.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
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+
# Use Python's highly optimized built-in sorting method (Timsort)
4+
arr.sort()
95
print(f"result: {arr}")
106
return arr

0 commit comments

Comments
 (0)