Skip to content

Commit 6f7004e

Browse files
Optimize sorter
The optimized bubble sort implements two key algorithmic improvements that significantly reduce unnecessary operations: **1. Early Exit Optimization**: The code adds a `swapped` flag to detect when the array becomes sorted during any pass. If no swaps occur in a complete pass, the array is already sorted and the algorithm terminates early. This is especially powerful for already-sorted or nearly-sorted data, as seen in the test results where sorted lists show dramatic speedups (99924% faster for large sorted lists). **2. Reduced Inner Loop Range**: The inner loop range changes from `range(len(arr) - 1)` to `range(len(arr) - 1 - i)`. After each outer loop iteration, the largest remaining element "bubbles up" to its correct position at the end, so there's no need to re-examine those already-sorted tail elements. **Performance Impact**: The line profiler shows the inner loop executes ~4.98M times vs ~14M times in the original (64% reduction). While the swapping operations remain identical (same number of swaps needed), the algorithm eliminates millions of redundant comparisons. The speedup is most pronounced on: - Already sorted data: 99924% faster (exits after first pass) - Lists with many duplicates: 7645% faster (becomes sorted quickly) - Mixed random data: 63-76% faster (fewer total comparisons) These optimizations maintain bubble sort's O(n²) worst-case complexity but achieve O(n) best-case performance when data is already sorted, making it much more practical for real-world scenarios where input data may have some existing order.
1 parent e0a80e9 commit 6f7004e

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

code_to_optimize/bubble_sort_3.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
def sorter(arr):
22
for i in range(len(arr)):
3-
for j in range(len(arr) - 1):
3+
swapped = False
4+
for j in range(len(arr) - 1 - i):
45
if arr[j] > arr[j + 1]:
56
temp = arr[j]
67
arr[j] = arr[j + 1]
78
arr[j + 1] = temp
9+
swapped = True
10+
if not swapped:
11+
break
812
return arr

0 commit comments

Comments
 (0)