Commit 1e0af23
authored
⚡️ Speed up function
Here is an **optimized** version of your function that preserves existing function signature and output. The current implementation uses [Bubble Sort](https://en.wikipedia.org/wiki/Bubble_sort), which is `O(n^2)`.
We can make multiple optimizations.
- **Use Python's built-in sort** for a drastic speedup (`Timsort`, O(n log n) in practice).
- Retain the print behavior.
Here's the rewritten code.
This will **dramatically reduce** runtime and memory overhead, since.
- It avoids unnecessary nested loops and swaps.
- Uses highly optimized C code underneath.
**Note:** If you must keep the swap logic for pedagogical reasons (Bubble Sort), you can still optimize.
- **Break early** if no swaps were made in a pass (best-case O(n)).
- **Decrease inner loop boundary** each pass.
Improved Bubble Sort.
**Recommendation**: Use the first (built-in) version for speed; use the improved bubble sort only if you have a reason not to use `.sort()`.sorter by 63%1 parent 4ab32b9 commit 1e0af23
1 file changed
+14
-0
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
0 commit comments