You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
0 commit comments