Commit 9ffbf72
authored
⚡️ Speed up function
The optimized code replaces a manual bubble sort implementation with Python's built-in `arr.sort()` method, achieving a **139,488% speedup** (from 3.65 seconds to 2.61 milliseconds).
**Key Optimization:**
- **Replaced O(n²) bubble sort with Timsort**: The original code used nested loops with O(n²) time complexity, performing up to 114 million iterations and 53 million swaps for larger inputs. The optimized version uses Python's highly optimized `sort()` method, which implements Timsort - a hybrid stable sorting algorithm with O(n log n) average case performance.
**Why This Works:**
- **Algorithm complexity**: Bubble sort's quadratic time complexity becomes prohibitively expensive as input size grows, while Timsort scales much better
- **Native C implementation**: Python's `sort()` is implemented in C and heavily optimized for real-world data patterns
- **Adaptive performance**: Timsort performs exceptionally well on already sorted or partially sorted data, explaining the massive speedups on ordered inputs (55,692% faster on sorted lists, 91,722% on reverse-sorted)
**Test Case Performance:**
- **Small lists (≤10 elements)**: Modest 8-36% improvements due to overhead being comparable
- **Large lists (1000 elements)**: Dramatic improvements of 10,000-90,000% faster, demonstrating the quadratic vs linearithmic complexity difference
- **Best for**: Large datasets, partially sorted data, and any production sorting needs where performance matters
The optimization maintains identical functionality, preserving in-place sorting behavior and all print statements.sorter by 139,489%1 parent bd320ee commit 9ffbf72
1 file changed
+2
-6
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | | - | |
4 | | - | |
5 | | - | |
6 | | - | |
7 | | - | |
8 | | - | |
| 3 | + | |
| 4 | + | |
9 | 5 | | |
10 | 6 | | |
0 commit comments