Skip to content

Commit 6abc215

Browse files
⚡️ Speed up function sorter by 145,189%
The optimization replaces a **manual bubble sort implementation** with Python's **built-in `arr.sort()` method**. **Key changes:** - Eliminated the nested O(n²) bubble sort loops that perform element-by-element comparisons and swaps - Replaced with Python's highly optimized Timsort algorithm (O(n log n) worst-case) **Why this leads to massive speedup:** - **Bubble sort complexity**: The original code performs ~n²/2 comparisons and up to n²/2 swaps for n elements - **Timsort efficiency**: Python's built-in sort is implemented in C, uses adaptive algorithms that perform well on partially sorted data, and has much better algorithmic complexity - **Memory access patterns**: Built-in sort has better cache locality compared to the random memory access pattern of bubble sort **Test case performance patterns:** - **Small lists (< 10 elements)**: Modest 10-45% improvements due to reduced Python interpreter overhead - **Large lists (1000 elements)**: Dramatic 10,000-90,000% speedups where algorithmic complexity dominates: - Already sorted: 57,607% faster (Timsort's adaptive nature shines) - Reverse sorted: 92,409% faster (worst case for bubble sort) - Random data: 44,000+ % faster (consistent O(n log n) vs O(n²) difference) The optimization is most effective for larger datasets where the O(n²) vs O(n log n) complexity difference becomes pronounced.
1 parent 83ee9c9 commit 6abc215

File tree

1 file changed

+1
-6
lines changed

1 file changed

+1
-6
lines changed

code_to_optimize/bubble_sort.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,5 @@
11
def sorter(arr):
22
print("codeflash stdout: Sorting list")
3-
for i in range(len(arr)):
4-
for j in range(len(arr) - 1):
5-
if arr[j] > arr[j + 1]:
6-
temp = arr[j]
7-
arr[j] = arr[j + 1]
8-
arr[j + 1] = temp
3+
arr.sort()
94
print(f"result: {arr}")
105
return arr

0 commit comments

Comments
 (0)