Commit ed02c9a
authored
⚡️ Speed up function
The optimized code achieves a **718% speedup** through two key algorithmic improvements:
**1. Mathematical Optimization of `calculate_pairwise_products`:**
- **Original:** O(n²) nested loops explicitly computing all pairs `arr[i] * arr[j]` where `i ≠ j`
- **Optimized:** O(n) mathematical formula using the identity: sum of all pairwise products = `total² - total_sq` where `total = sum(arr)` and `total_sq = sum(x² for x in arr)`
- **Impact:** Reduces ~28.2 seconds to ~7ms for large arrays (99.97% reduction in this function's runtime)
**2. Bubble Sort Early Termination:**
- **Original:** Always performs full passes through the entire array
- **Optimized:**
- Reduces inner loop range by `i` each iteration since last `i` elements are already sorted
- Adds `already_sorted` flag to exit early when no swaps occur
- **Impact:** Reduces sorting time from ~16.2 seconds to ~6.6 seconds (59% improvement)
**Performance by Test Case Type:**
- **Large uniform arrays** (1000 elements, same values): ~77,000% faster due to mathematical optimization
- **Large sequential/random arrays**: ~300-800% faster from combined optimizations
- **Small arrays** (<10 elements): Minimal improvement (0-20%) as overhead dominates
- **Edge cases** (zeros, negatives): Consistent improvements across all sizes
The mathematical optimization dominates performance gains for large arrays since it eliminates the quadratic bottleneck in pairwise product calculation.compute_and_sort by 719%1 parent 8753e54 commit ed02c9a
File tree
2 files changed
+14
-14
lines changed- code_to_optimize
2 files changed
+14
-14
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | 3 | | |
4 | | - | |
| 4 | + | |
| 5 | + | |
5 | 6 | | |
6 | 7 | | |
7 | 8 | | |
8 | 9 | | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
9 | 13 | | |
10 | 14 | | |
Lines changed: 9 additions & 13 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | 3 | | |
4 | | - | |
5 | | - | |
6 | | - | |
7 | | - | |
8 | | - | |
9 | | - | |
10 | 4 | | |
11 | | - | |
12 | | - | |
13 | | - | |
14 | | - | |
15 | | - | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
16 | 14 | | |
17 | | - | |
18 | | - | |
19 | 15 | | |
20 | 16 | | |
21 | 17 | | |
| |||
0 commit comments