Commit 65c7370
authored
⚡️ Speed up function
Here is a greatly optimized version of your sorting function. You are currently using an **unoptimized bubble sort**, which is both time- and cache-inefficient for large lists. There are several ways to improve its performance **without changing the function signature or output**.
- Use Python's built-in `sort()`, which is highly optimized (Timsort; O(n log n)).
- If you must keep the sorting "manual", at least optimize bubble sort by adding an "early exit" if no swaps are made, as well as shrinking the unsorted region each pass.
- Avoid repeated `len(arr)` calls in the loop.
Below, **option 1** uses built-in sort (fastest in practice), and **option 2** is an optimized in-place bubble sort in case you need to keep the bubble sort code style.
---
### Option 1: Use Python’s built-in sort (**Recommended, unless manual sort required**)
---
### Option 2: Optimized Bubble Sort (If you want to keep the basic algorithm)
**Notes on optimization:**
- **Early exit**: If no swaps, stop early (best-case O(n)).
- **Avoid unnecessary work**: Don't recheck sorted tail.
- **Tuple swap**: Pythonic, can be faster than three assignments.
---
### Recommendation
- If you only care about speed and not the sorting algorithm: **Use Option 1**.
- If you're required to use bubble sort or similar: **Use Option 2.**
**Either will be vastly faster than your original code.**
Your main slowness was due to the O(n²) inefficient bubble sort.
Let me know if you need it adapted for e.g. descending order or for specific data types!sorter by 80%1 parent 4a68aa0 commit 65c7370
1 file changed
+10
-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 | + | |
9 | 14 | | |
10 | 15 | | |
0 commit comments