Skip to content

Commit 9e265b7

Browse files
⚡️ Speed up function sorter by 56,879%
Certainly! The current implementation uses Bubble Sort, which has a time complexity of \(O(n^2)\). We can improve the efficiency significantly by using built-in sorting functions which are optimized for performance. Here is the optimized program. In this version, we replaced the Bubble Sort with the `sort` method, which utilizes Timsort, a hybrid stable sorting algorithm derived from merge sort and insertion sort.
1 parent 67d3f19 commit 9e265b7

File tree

1 file changed

+4
-6
lines changed

1 file changed

+4
-6
lines changed

code_to_optimize/bubble_sort.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
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+
4+
# Using built-in sort method which uses Timsort with a time complexity of O(n log n)
5+
arr.sort()
6+
97
print(f"result: {arr}")
108
return arr

0 commit comments

Comments
 (0)