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's an optimized version of your code.
### Major improvements.
- **Use Python built-in sort:** The original code is an unoptimized bubble sort (`O(n^2)`), while Python's built-in `sort` runs in `O(n log n)` and is highly optimized in C.
- **If you must keep the in-place sorting and returning of `arr`, just use `arr.sort()`.**
- **All variable swapping is handled internally by Python efficiently.**
#### If you want to keep a manual fast sort (like quicksort), consider.
### Why this is faster.
- Removes unnecessary Python for-loops and variable swaps.
- Built-ins leverage C speed and tim-sort algorithm.
- **Behavior is identical:** sorts `arr` in-place and returns it.
---
If you need a manual algorithm for educational purposes (not recommended for production), I can provide a fast implementation (e.g., using quicksort or heapsort), but for 99% of use cases, the above is best for speed and memory!
0 commit comments