Commit 68fbd26
authored
⚡️ Speed up method
The optimization replaces a naive O(n²) bubble sort implementation with Python's built-in `arr.sort()` method, which uses Timsort - a highly optimized O(n log n) hybrid stable sorting algorithm.
**Key changes:**
- Removed the nested loop bubble sort implementation (lines with `for i in range(len(arr))` and `for j in range(len(arr) - 1)`)
- Replaced the manual element swapping logic with a single `arr.sort()` call
- Maintained in-place sorting behavior and return value
**Why this is faster:**
1. **Algorithmic complexity**: Bubble sort is O(n²) while Timsort is O(n log n), providing exponential speedup for larger datasets
2. **Implementation efficiency**: Python's built-in sort is implemented in optimized C code vs. interpreted Python loops
3. **Adaptive behavior**: Timsort performs even better on partially sorted data, explaining the massive speedups on already-sorted test cases
**Performance results by test case type:**
- **Small lists (≤10 elements)**: 70-216% faster due to reduced function call overhead
- **Large sorted/reverse-sorted lists**: 676,311-987,901% faster as Timsort detects patterns and optimizes accordingly
- **Large random lists**: 65,882-71,127% faster from the fundamental algorithmic improvement
- **Lists with many duplicates**: 96,999-105,372% faster as Timsort handles duplicates efficiently
The optimization maintains identical behavior including in-place mutation, return value, and exception handling for incomparable elements.Sorter.sort_class by 113,722%1 parent 8753e54 commit 68fbd26
1 file changed
+6
-6
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
| 2 | + | |
| 3 | + | |
2 | 4 | | |
3 | 5 | | |
4 | 6 | | |
| |||
9 | 11 | | |
10 | 12 | | |
11 | 13 | | |
| 14 | + | |
12 | 15 | | |
13 | 16 | | |
14 | 17 | | |
| |||
27 | 30 | | |
28 | 31 | | |
29 | 32 | | |
| 33 | + | |
30 | 34 | | |
31 | 35 | | |
32 | 36 | | |
33 | 37 | | |
| 38 | + | |
34 | 39 | | |
35 | 40 | | |
36 | 41 | | |
| |||
55 | 60 | | |
56 | 61 | | |
57 | 62 | | |
58 | | - | |
59 | | - | |
60 | | - | |
61 | | - | |
62 | | - | |
63 | | - | |
| 63 | + | |
64 | 64 | | |
0 commit comments