Commit 9192615
authored
⚡️ Speed up function
Here’s an optimized version of your `sorter` function. The original is an unoptimized Bubble Sort, which is quite slow. A **much faster way in Python** is to use the built-in `sort()` or `sorted()` functions, but to stay true to the original intent (in-place sort, return the array, don't change function name/signature), I'll use that.
However, if you want to **stay as close as possible to the original logic but make it much faster**, you can.
1. Avoid repeated `len(arr)` calls by storing the length.
2. Notice that with each pass, the largest remaining item is at the end, so the inner loop can shrink.
3. Add early exit if no swaps occur (optimization for already nearly-sorted input).
Here's your function rewritten with those optimizations.
**Explanation of optimizations:**
- `n = len(arr)` stores length, saving recalculation.
- Inner loop does not consider elements already sorted at the end (`n - i - 1`).
- `swapped` flag allows breaking early if the array is sorted before all passes.
- Tuple swap is slightly faster and cleaner than using a temp variable.
If you require the absolute fastest sort, simply call `arr.sort()` and return `arr`. If not, this is the fastest idiomatic bubble sort.
Let me know if you want a solution that simply uses `arr.sort()` (which is based on Timsort and much faster for real data)!sorter by 84%1 parent 5aab3b8 commit 9192615
1 file changed
+8
-5
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | | - | |
3 | | - | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
4 | 6 | | |
5 | | - | |
6 | | - | |
7 | | - | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
8 | 11 | | |
0 commit comments