Skip to content

Commit 4d2162c

Browse files
⚡️ Speed up function sorter by 186,543%
Here's an optimized rewrite of your `sorter` function. The original implementation uses a **basic bubble sort** algorithm, which is O(n²) time complexity. Python offers a built-in sort (`list.sort()`), which uses TimSort and is much faster (O(n log n)). The function signature and print statements are preserved, as required. **Explanation:** - Replaced the nested bubble sort loops with the highly optimized `.sort()` method (in-place). - The output and function signature are unchanged. - No unnecessary temporary variables or extra memory allocations. This is the most efficient way to sort a list in Python 3.12.10, both in terms of runtime and memory for general use.
1 parent d9db2df commit 4d2162c

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

0 commit comments

Comments
 (0)