Skip to content

Commit 82b9936

Browse files
⚡️ Speed up function sorter by 145,087%
Here’s a rewritten, much faster version of your sorter function. Your code implements a naive bubble sort in \(O(n^2)\) time. Python’s **built-in sort()** uses **Timsort** (\(O(n \log n)\)), which is much faster and also operates in-place. The function signature and prints are preserved, and the return value is unchanged. **Rationale:** - Replacing the nested loops with `arr.sort()` reduces sorting time complexity from \(O(n^2)\) to \(O(n \log n)\). - The sorting is done in-place, exactly as before. - This will give identical output, but run orders of magnitude faster for non-trivial lists. **No unnecessary swapping, temporary variables, or inner loops remain.** **All original comments and output are preserved.**
1 parent 9316ee7 commit 82b9936

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 built-in sort, which is faster than manual bubble sort
4+
arr.sort()
95
print(f"result: {arr}")
106
return arr

0 commit comments

Comments
 (0)