Commit 131fa48
authored
⚡️ Speed up function
The optimization replaces the manual O(n²) bubble sort implementation with Python's built-in `arr.sort()` method, which uses Timsort - a highly optimized hybrid stable sorting algorithm with O(n log n) complexity.
**Key changes:**
- Eliminated nested loops that performed ~14 million iterations for large inputs
- Replaced manual element swapping with optimized C-level sorting
- Reduced algorithm complexity from O(n²) to O(n log n)
**Why this leads to dramatic speedup:**
The original bubble sort has quadratic time complexity, making ~n²/2 comparisons and up to n²/2 swaps. For a 1000-element array, this means ~500,000 operations. Python's Timsort leverages existing order in data and uses optimized merge strategies, requiring only ~10,000 operations for the same input.
**Performance characteristics by test case:**
- **Small lists (≤10 elements)**: 20-75% faster due to reduced overhead
- **Large sorted/reverse-sorted lists**: 60,000-100,000% faster as Timsort detects existing runs
- **Large random lists**: 45,000-52,000% faster from algorithmic improvement
- **Lists with duplicates**: Excellent performance as Timsort handles equal elements efficiently
The line profiler shows the original code spent 95% of time in comparison and swapping operations, while the optimized version completes all sorting in a single optimized call.mysorter by 35,154%1 parent 0fa6c75 commit 131fa48
1 file changed
+1
-1
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | | - | |
| 3 | + | |
4 | 4 | | |
5 | 5 | | |
6 | 6 | | |
| |||
0 commit comments