Skip to content

Commit 101142e

Browse files
⚡️ Speed up function sorter by 57,106%
Certainly! The given program uses bubble sort, which has an average and worst-case time complexity of \(O(n^2)\). We can optimize this by using a more efficient sorting algorithm like Timsort, which is the default sorting algorithm used in Python's `sorted()` method and `list.sort()` method. Timsort has a time complexity of \(O(n \log n)\). Here's the modified code. This code calls the `arr.sort()` method that sorts the list in place using Timsort, making it significantly faster for larger lists.
1 parent f4be9be commit 101142e

File tree

1 file changed

+2
-6
lines changed

1 file changed

+2
-6
lines changed

code_to_optimize/bubble_sort.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
11
def sorter(arr):
2+
"""Sorts a list using Python's built-in Timsort algorithm."""
23
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
4+
arr.sort()
95
print(f"result: {arr}")
106
return arr

0 commit comments

Comments
 (0)