Commit 97d88ac
authored
⚡️ Speed up function
Here's an optimized version of your program.
**Your code uses bubble sort with unnecessary recomputation of `len(arr)`. Instead, use Python’s built-in sort (which is in-place and much, much faster).**
If you want to preserve the manual sort for educational purposes, at least minimize attribute and function calls by keeping the length calculation outside of the loop, and **exit early if no swaps were performed** (classic bubble sort optimization).
But, for runtime, the built-in sort is best. Since your function returns the sorted array in-place, this is a drop-in replacement.
**Fastest version (use built-in sort):**
---
**If you want to keep a manual implementation with loop optimizations and swap-detection:**
This **avoids unnecessary passes** and decreases the inner loop range as elements bubble up.
---
**Summary:**
- Use `arr.sort()` for best speed in production.
- If you must show sorting logic, use the manually optimized Bubble Sort shown above.
Both return the array as before and print the same messages.sorter by 56%1 parent 58e44d3 commit 97d88ac
1 file changed
+12
-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 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
9 | 16 | | |
10 | 17 | | |
0 commit comments