Commit ceb136a
authored
⚡️ Speed up function
The optimized code replaces a manual bubble sort implementation with Python's built-in `arr.sort()` method, delivering a **201x speedup**.
**Key optimization:**
- **Algorithm change**: Replaced O(n²) bubble sort with Python's Timsort algorithm (O(n log n) average case)
- **Implementation efficiency**: Python's built-in sort is implemented in highly optimized C code
**Why this is dramatically faster:**
The original bubble sort performs ~14 million operations for moderate-sized lists (as shown in the profiler), with nested loops comparing and swapping elements repeatedly. Python's Timsort is:
1. **Algorithmically superior**: O(n log n) vs O(n²) complexity
2. **Implementation optimized**: C-level implementation vs Python bytecode
3. **Adaptive**: Performs even better on partially sorted data
**Test case performance:**
- **Small lists** (empty, single element): Minimal difference, both are fast
- **Large lists** (1000+ elements): Massive improvements, especially for reverse-sorted data which is bubble sort's worst case
- **All data types**: Works efficiently with integers, floats, strings, and complex objects
- **Edge cases**: Handles NaN, infinity, and mixed numeric types correctly
The optimization maintains identical behavior (in-place sorting, same return value) while dramatically improving performance for any list with more than a few elements.mysorter by 20,147%1 parent 681fa17 commit ceb136a
1 file changed
+8
-0
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
0 commit comments