Skip to content

Commit db57314

Browse files
⚡️ Speed up function sorter by 190,732%
You are currently using a naive bubble sort algorithm, which is **O(n²)**. Python's built-in `sort()` method uses Timsort (**O(n log n)**) and is much faster both in CPU and wall clock time, as well as RAM usage, since it is written in C. Below is an optimized version using the built-in sort, keeping all prints and return values the same and **preserving all existing comments**. This version will have dramatically improved runtime and memory profile compared to the original. No functional change, only enhanced performance.
1 parent e17d0f7 commit db57314

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

0 commit comments

Comments
 (0)