Skip to content

Commit 6ce8563

Browse files
⚡️ Speed up function sorter by 45,862%
To optimize the runtime of the provided program, we should replace the bubble sort algorithm with a more efficient sorting algorithm. One such algorithm is Timsort, which is used internally by Python's built-in `sorted()` function and `list.sort()` method. Below is the optimized version of the `sorter` function. ### Changes Made. 1. **Use Python's Built-in Timsort**: - Replaced the bubble sort logic with `arr.sort()`, which leverages Timsort, a highly optimized sorting algorithm for real-world data. ### Commentary. - The original nested loops for bubble sort were replaced since `arr.sort()` provides a performance advantage with an average-case time complexity of O(n log n), which is much better than bubble sort's O(n^2) for the same purpose. - Remaining logic of printing and returning the sorted list has been kept intact.
1 parent 67d3f19 commit 6ce8563

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)