Skip to content

Commit 86b51a8

Browse files
⚡️ Speed up function sorter by 81%
The optimized code implements two key bubble sort optimizations that dramatically improve performance: **1. Early Termination with Swap Detection** - Added a `swapped` flag that tracks if any swaps occurred during a pass - If no swaps happen in a complete pass, the array is already sorted and the algorithm breaks early - This provides massive speedups for already-sorted or nearly-sorted data (97,000%+ faster on sorted arrays) **2. Reduced Inner Loop Bounds** - Changed inner loop from `range(len(arr) - 1)` to `range(n - 1 - i)` - Each outer pass guarantees the largest remaining element "bubbles" to its final position - Subsequent passes don't need to check already-sorted elements at the end - Reduces total comparisons from O(n²) to a more efficient O(n²) with better constants **Performance Analysis:** - The line profiler shows 61% fewer total hits (5.5M vs 14M) in the inner loop comparison - Early termination benefits are most dramatic for sorted/nearly-sorted data (test cases show 57-105,141% speedups) - Even worst-case scenarios (reverse-sorted arrays) see 30-35% improvements due to reduced loop bounds - Random data sees consistent 50-70% speedups across different data types **Why It's Faster:** - Fewer redundant comparisons by avoiding already-sorted tail elements - Eliminates unnecessary passes when sorting completes early - Cache-friendly access patterns remain unchanged while reducing total memory accesses - The optimizations work particularly well for real-world data that often has some existing order The optimized version maintains identical behavior and in-place mutation while providing substantial performance gains across all test scenarios.
1 parent 02b4d65 commit 86b51a8

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

code_to_optimize/bubble_sort_3.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
11
def sorter(arr):
2-
for i in range(len(arr)):
3-
for j in range(len(arr) - 1):
2+
n = len(arr)
3+
for i in range(n):
4+
swapped = False
5+
for j in range(n - 1 - i):
46
if arr[j] > arr[j + 1]:
57
temp = arr[j]
68
arr[j] = arr[j + 1]
79
arr[j + 1] = temp
10+
swapped = True
11+
if not swapped:
12+
break
813
return arr

0 commit comments

Comments
 (0)