Skip to content

Commit 2944436

Browse files
⚡️ Speed up function sorter by 49,820%
Here's the optimized version of the given Python program, which improves the sorting algorithm from a bubble sort (`O(n^2)`) to a more efficient algorithm like Timsort (`O(n log n)`). **Explanation:** - I replaced the bubble sort algorithm with the built-in `sort()` method of Python lists. The built-in sort method in Python uses Timsort, which is an adaptive, stable, and efficient sorting algorithm derived from merge sort and insertion sort. - This change dramatically reduces the complexity from `O(n^2)` to `O(n log n)`, resulting in significantly faster sorting, especially for larger lists.
1 parent 67d3f19 commit 2944436

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, which is Python's built-in sorting algorithm
94
print(f"result: {arr}")
105
return arr

0 commit comments

Comments
 (0)