Commit 78afb3d
authored
⚡️ Speed up function
Here’s a much faster rewritten version of your program. Your original implementation is a classic **bubble sort** (O(n²)) with redundant passes and repeated calls to `len(arr)`. The program can be made significantly faster by.
- Using Python's built-in `sort()`, which uses Timsort (O(n log n)).
- Alternatively, if you wish to keep the explicit algorithm, using an optimized Bubble Sort that stops when the list is already sorted, and reduces the inner loop length by each completed pass.
- Reducing repeated attribute lookups (e.g., store `len(arr)` once).
- Removing unnecessary data swaps (`temp`) by using Python tuple assignment.
The **fastest** you can get is with the built-in sort, but if you must use your own loop (since you want the print statements to output the same way and avoid return value changes), here are both options.
---
**Option 1: Fastest Built-in Sort**
---
**Option 2: Optimized Bubble Sort (if custom algorithm is required)**
---
**Explanation of the optimization:**
- `arr.sort()` leverages Python's Timsort, which is much faster and memory-efficient for almost all practical purposes.
- For the manual method, reducing passes and skipping redundant comparisons makes it much faster (`O(n²)` worst, `O(n)` best).
- Early exit if no swaps (already sorted).
- Reduced function overhead and Python list indexing looks.
*Both options retain exactly the print outputs and function return of the original. Use Option 1 unless your requirements specifically forbid `sort()`.*sorter by 83%1 parent 2185af9 commit 78afb3d
1 file changed
+9
-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 | + | |
9 | 13 | | |
10 | 14 | | |
0 commit comments