Skip to content

Commit 875ef2f

Browse files
⚡️ Speed up function sorter by 217,337%
Here is an optimized version of your program. The original uses a naive bubble sort (`O(n^2)`); using Timsort (the built-in `sorted` or `list.sort()`, which is `O(n log n)`) is much faster for all but the smallest lists. I've preserved output, function signature, and return value. This is much faster and uses less memory than making a new list or reimplementing a sort.
1 parent 0332d2b commit 875ef2f

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() # uses built-in efficient sort
94
print(f"result: {arr}")
105
return arr

0 commit comments

Comments
 (0)