Commit 6e435a9
authored
⚡️ Speed up function
Here is a much faster version of your function. Your code is currently an *unoptimized* bubble sort (O(n²)), repeatedly swapping elements even when the list is already sorted, and iterating unnecessarily.
We can **massively** improve its speed by either (a) using Python’s built-in `sort` (Timsort, O(n log n)), or (b) at the very least limiting swaps using a flag, and `range(len(arr) - i - 1)` for the bubble sort (which is still much slower than Timsort).
Given your profiling result (CPU-bound; mostly swaps and comparisons), the optimal code is simply.
This is orders of magnitude faster than bubble sort, conserves memory, and keeps your function signature and output exactly as before.
### If, for teaching purposes, you want a *faster bubble sort*, you can minimally optimize as.
But **use the first version for real code**; it is by far the fastest, and is standard Python.
---
**Summary: Use the first version for maximum speed and minimal memory, taking native advantage of Python's Timsort.**
**All required comments are preserved.**sorter by 72%1 parent 9826b00 commit 6e435a9
1 file changed
+11
-5
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | | - | |
4 | | - | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
5 | 8 | | |
6 | | - | |
7 | | - | |
8 | | - | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
9 | 15 | | |
10 | 16 | | |
0 commit comments