Skip to content

Commit ed02c9a

Browse files
⚡️ Speed up function compute_and_sort by 719%
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.
1 parent 8753e54 commit ed02c9a

File tree

2 files changed

+14
-14
lines changed

2 files changed

+14
-14
lines changed

code_to_optimize/bubble_sort.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
11
def sorter(arr):
22
print("codeflash stdout: Sorting list")
33
for i in range(len(arr)):
4-
for j in range(len(arr) - 1):
4+
already_sorted = True
5+
for j in range(len(arr) - i - 1):
56
if arr[j] > arr[j + 1]:
67
temp = arr[j]
78
arr[j] = arr[j + 1]
89
arr[j + 1] = temp
10+
already_sorted = False
11+
if already_sorted:
12+
break
913
print(f"result: {arr}")
1014
return arr

code_to_optimize/process_and_bubble_sort_codeflash_trace.py

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,17 @@
11
from code_to_optimize.bubble_sort import sorter
22
from codeflash.benchmarking.codeflash_trace import codeflash_trace
33

4-
def calculate_pairwise_products(arr):
5-
"""
6-
Calculate the average of all pairwise products in the array.
7-
"""
8-
sum_of_products = 0
9-
count = 0
104

11-
for i in range(len(arr)):
12-
for j in range(len(arr)):
13-
if i != j:
14-
sum_of_products += arr[i] * arr[j]
15-
count += 1
5+
def calculate_pairwise_products(arr):
6+
"""Calculate the average of all pairwise products in the array."""
7+
if len(arr) < 2:
8+
return 0
9+
total = sum(arr)
10+
total_sq = sum(x * x for x in arr)
11+
sum_of_products = total * total - total_sq
12+
count = len(arr) * (len(arr) - 1)
13+
return sum_of_products / count
1614

17-
# The average of all pairwise products
18-
return sum_of_products / count if count > 0 else 0
1915

2016
@codeflash_trace
2117
def compute_and_sort(arr):

0 commit comments

Comments
 (0)