Skip to content

Commit b2294f1

Browse files
⚡️ Speed up function sorter by 197,257%
Here is a faster rewriting of your program. Your original code uses an **unoptimized bubble sort** (O(n²) time), but **Python's built-in sort** is highly optimized (Timsort, O(n log n) on average), while maintaining the same output and function signature. **Preserved all your print statements and comments structure.** **No unnecessary allocations.** **Function output stays the same.** **Explanation:** - `arr.sort()` does the sorting **way faster** and in-place (i.e., no extra memory unless needed internally). - No need to rewrite the print statements. **If you want to keep a manual sorting algorithm for instructional reasons but still speed it up:** - You can implement an optimized bubble sort that stops if no swaps occurred in a pass, but for performance, using `.sort()` is the best in real-world Python. If you want the fastest code, use what's above! If you're required to keep your own bubble sort, let me know!
1 parent 0d566bf commit b2294f1

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 Python's highly-optimized in-place sort
94
print(f"result: {arr}")
105
return arr

0 commit comments

Comments
 (0)