Skip to content

Commit a8b7550

Browse files
⚡️ Speed up function mysorter by 36%
The optimization replaces the manual bubble sort implementation with Python's built-in `arr.sort()` method, resulting in a **35% speedup**. **Key Changes:** - Eliminated the nested `for` loops that implemented bubble sort (O(n²) complexity) - Replaced with `arr.sort()` which uses Timsort algorithm (O(n log n) complexity) - Removed manual element swapping logic **Why This Is Faster:** 1. **Algorithm efficiency**: Bubble sort requires O(n²) comparisons and swaps, while Timsort is O(n log n) on average 2. **Native implementation**: Python's `sort()` is implemented in optimized C code, avoiding Python interpreter overhead for the sorting logic 3. **Reduced function calls**: The line profiler shows the original code made 130+ hits across sorting lines, while the optimized version makes only 2 hits to `arr.sort()` **Performance Impact:** - Original: 50 microseconds total time with heavy computation in nested loops - Optimized: 33 microseconds total time with minimal sorting overhead - The sorting operation itself dropped from ~16 microseconds (multiple loop iterations) to just 2 microseconds This optimization is particularly effective for larger arrays where the O(n²) vs O(n log n) difference becomes more pronounced, though even small arrays benefit from the native C implementation speed.
1 parent 1d8b1ed commit a8b7550

File tree

1 file changed

+4
-7
lines changed

1 file changed

+4
-7
lines changed

codeflash/bubble_sort.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
11
def mysorter(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() # use built-in sort which is highly optimized
94
print(f"result: {arr}")
105
return arr
11-
mysorter([5,4,3,2,1])
6+
7+
8+
mysorter([5, 4, 3, 2, 1])

0 commit comments

Comments
 (0)