Skip to content

Commit 8660074

Browse files
⚡️ Speed up function sorter by 222,606%
The optimization replaces a manual bubble sort implementation with Python's built-in `arr.sort()` method, achieving a **222,606% speedup** by eliminating the O(n²) nested loops. **Key Changes:** - **Removed nested loops**: The original code used two nested `for` loops that resulted in O(n²) time complexity, executing millions of comparisons and swaps for larger arrays - **Used built-in sort**: Python's `list.sort()` uses Timsort algorithm with O(n log n) average complexity and is implemented in highly optimized C code **Why This Creates Massive Speedup:** - **Algorithmic improvement**: O(n²) → O(n log n) means exponentially fewer operations as data size grows - **Native implementation**: Built-in sort runs in C, avoiding Python interpreter overhead for each comparison/swap - **Optimized for real-world data**: Timsort performs exceptionally well on partially sorted data and handles duplicates efficiently **Performance by Test Case Type:** - **Small arrays (≤10 elements)**: 25-93% faster due to reduced function call overhead - **Large arrays (1000 elements)**: 8,945% to 104,669% faster, with the largest gains on reverse-sorted data where bubble sort performs worst - **Edge cases**: Consistent 40-85% improvements even for special values (NaN, infinity, mixed types) The optimization maintains identical behavior - same in-place sorting, same return value, same error handling - while dramatically reducing computational complexity.
1 parent f681c0f commit 8660074

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)