Skip to content

Commit d691834

Browse files
⚡️ Speed up function sorter by 325,341%
Certainly! The given program uses a basic and inefficient bubble sort algorithm. We can optimize it by using Python’s built-in `sort` method which is highly optimized. Here's the rewritten code. This change will leverage Timsort, the algorithm used in Python's built-in sort, which has an average-case time complexity of O(n log n) and is much faster than bubble sort. The output and functionality remain exactly the same.
1 parent 832b2eb commit d691834

File tree

1 file changed

+5
-7
lines changed

1 file changed

+5
-7
lines changed

code_to_optimize/bubble_sort.py

Lines changed: 5 additions & 7 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 the built-in sort method which is more efficient
5+
arr.sort()
6+
97
print(f"result: {arr}")
10-
return arr
8+
return arr

0 commit comments

Comments
 (0)