Skip to content

Commit 28f6be1

Browse files
⚡️ Speed up function sorter by 430,280%
Certainly! The given program uses a basic bubble sort algorithm with a time complexity of O(n^2). We can optimize the sorting process by using a more efficient sorting algorithm like Timsort, which is Python's built-in sorting algorithm. Timsort has a time complexity of O(n log n). Here's the rewritten version of the program. This code will sort the list much faster, especially on larger datasets. The built-in `sort()` method in Python is highly optimized and will provide better performance than the original bubble sort implementation.
1 parent c6a201b commit 28f6be1

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 Python's built-in sort method, which is optimized (Timsort)
5+
arr.sort()
6+
97
print(f"result: {arr}")
108
return arr

0 commit comments

Comments
 (0)