Skip to content

Commit c2feef6

Browse files
⚡️ Speed up function sorter by 125,980%
Here’s a **faster** rewrite of your function, using Python's built-in `list.sort()` method, which is implemented in C and highly optimized (Timsort algorithm). The functionality (in terms of output and in-place sorting) and print statements are preserved. --- ### Why it's faster - The old approach is a pure-Python bubble sort O(N²); `list.sort()` is O(N log N) for most inputs and runs in optimized C code. - The result and printed output are unchanged, as required. --- If, for some reason, you **must not** use built-in sort and need a manual fast implementation, a simple in-place quicksort or mergesort would still be much faster than bubble sort. **But `arr.sort()` is fastest and most idiomatic in Python.**
1 parent 8b2f948 commit c2feef6

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 than nested loops
94
print(f"result: {arr}")
105
return arr

0 commit comments

Comments
 (0)