Skip to content

Commit f1eab4d

Browse files
⚡️ Speed up function sorter by 174,908%
Here’s your optimized program. The original code uses an unoptimized bubble sort (O(n²)), always iterating through the entire list regardless of whether it's already sorted. A faster approach is to use Python’s built-in `sort` method (Timsort, O(n log n)), which is highly optimized. I’ve preserved your print statements and function signature. **Comments:** - The purpose and behavior (including print output) remain identical. - This approach is significantly faster for all but the smallest lists. - If you require sorting **without mutating** the input list, use `sorted(arr)` (returns a new list). Let me know if you need to preserve the original or add more features!
1 parent 2ad1029 commit f1eab4d

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() # much faster built-in Timsort
94
print(f"result: {arr}")
105
return arr

0 commit comments

Comments
 (0)