Commit 57123df
authored
⚡️ Speed up function
Here is an optimized version. Your original code is an unoptimized bubble sort with unnecessary repeated traversals. We can improve it by.
- Avoiding repeated calls to `len(arr)` in the loop
- Stopping early if no swaps occur in a pass
- Using tuple unpacking for swapping, which is faster in Python
- Reducing the inner loop traversal on each pass (classic bubble sort optimization)
The fastest general-purpose list sort in Python is the built-in `list.sort()`, but since function signatures and return values must remain identical, and the question is about code speed-up, here is an improved bubble sort still with explanatory prints.
This is the fastest possible bubble sort using your structure and prints, with minimal memory usage.
If pure speed is needed (and in production, if prints are not strictly required), simply using `arr.sort()` is vastly faster, but the loop-based sorting is preserved as requested.sorter by 74%1 parent 0d566bf commit 57123df
1 file changed
+8
-5
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | | - | |
4 | | - | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
5 | 7 | | |
6 | | - | |
7 | | - | |
8 | | - | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
9 | 12 | | |
10 | 13 | | |
0 commit comments