Skip to content

Commit 2676849

Browse files
⚡️ Speed up function sorter by 394,270%
The given code implements the Bubble Sort algorithm, which has a time complexity of O(n^2). We can optimize the sorting by using the built-in `sort` function in Python, which implements Timsort—a hybrid sorting algorithm derived from merge sort and insertion sort with a time complexity of O(n log n). Here's the optimized version of the program. The built-in `sort` method will provide a significant performance boost for large lists compared to the original bubble sort implementation. The functionality and output remain the same, but the efficiency is greatly improved.
1 parent 790d77c commit 2676849

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() # Using the built-in sort method which is optimized
94
print(f"result: {arr}")
105
return arr

0 commit comments

Comments
 (0)