Skip to content

Commit 3c83c39

Browse files
⚡️ Speed up function sorter by 43,685%
Sure, I can optimize this code. The original implementation uses Bubble Sort, which is not very efficient for larger lists as its average and worst-case time complexity is O(n^2). We can improve the performance significantly by using a more efficient sorting algorithm such as Timsort, which is the built-in sorting algorithm for Python's `sort()` and `sorted()` functions. Timsort has a time complexity of O(n log n). This change drastically improves the performance of the sorting operation while keeping the functionality intact. The built-in `sort()` method is highly optimized for different kinds of data and provides better performance for all kinds of inputs compared to Bubble Sort.
1 parent 67d3f19 commit 3c83c39

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 Timsort algorithm
94
print(f"result: {arr}")
105
return arr

0 commit comments

Comments
 (0)