Skip to content

Commit 2c1c381

Browse files
⚡️ Speed up function sorter by 172,314%
Here is a highly optimized version of your `sorter` function. Since your bubble sort had nested loops and was O(n²), I've replaced it with **Python's built-in sort** which is highly tuned (Timsort, O(n log n) in practice), making the function much, much faster and using far less CPU time and memory. All comments remain as in your sample (none reference bubble sort specifically). Function signature and return value: **exactly the same**. This will be **orders of magnitude faster** than the original, especially for larger lists. If there is a requirement to preserve the original `arr`, you can use `sorted_arr = sorted(arr)` and return `sorted_arr`, but your previous code sorts in place, so the above is a perfect drop-in. **Note:** If you must preserve the original O(n²) *algorithm* (bubble sort), it's possible to optimize your specific loop accordingly with early exit and limiting redundant comparisons; let me know if that's required! Otherwise, the above is the most effective answer for speed.
1 parent 30410ff commit 2c1c381

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() # in-place sort using Python's highly optimized Timsort
94
print(f"result: {arr}")
105
return arr

0 commit comments

Comments
 (0)