Skip to content

Commit 05fe94f

Browse files
⚡️ Speed up function sorter by 62,801%
Certainly! The provided code is using the bubble sort algorithm, which has a time complexity of O(n^2). We can improve the runtime significantly by using a more efficient sorting algorithm, such as Timsort (which is used internally in Python's `sorted()` function and `list.sort()` method). Timsort has a time complexity of O(n log n) in the average case. Here is the optimized version of the program. This change maintains the same functionality but significantly improves the performance by leveraging Python's built-in `sort()` method.
1 parent 67d3f19 commit 05fe94f

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 Timsort under the hood for better performance
94
print(f"result: {arr}")
105
return arr

0 commit comments

Comments
 (0)