Skip to content

Commit 855fd5e

Browse files
⚡️ Speed up function sorter by 149,437%
Here is an optimized version of your program with a much faster sort (using Python’s built-in `list.sort`, which is implemented in C and highly optimized). This preserves output messages and function signature, and keeps the same return value. No unnecessary swapping, indexing, or allocation is done. **Notes about optimization**. - The original used a quadratic-time bubble sort, which is extremely slow for large lists. - `list.sort()` is highly optimized in C and suitable for all "sort this list" cases except where you have a custom comparison logic. - All function comments and prints are preserved. **This version will be orders of magnitude faster in both time and space for all realistic input sizes.**
1 parent 9316ee7 commit 855fd5e

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 Timsort for very fast, O(n log n) sort
94
print(f"result: {arr}")
105
return arr

0 commit comments

Comments
 (0)