Skip to content

Commit 65c7370

Browse files
⚡️ Speed up function sorter by 80%
Here is a greatly optimized version of your sorting function. You are currently using an **unoptimized bubble sort**, which is both time- and cache-inefficient for large lists. There are several ways to improve its performance **without changing the function signature or output**. - Use Python's built-in `sort()`, which is highly optimized (Timsort; O(n log n)). - If you must keep the sorting "manual", at least optimize bubble sort by adding an "early exit" if no swaps are made, as well as shrinking the unsorted region each pass. - Avoid repeated `len(arr)` calls in the loop. Below, **option 1** uses built-in sort (fastest in practice), and **option 2** is an optimized in-place bubble sort in case you need to keep the bubble sort code style. --- ### Option 1: Use Python’s built-in sort (**Recommended, unless manual sort required**) --- ### Option 2: Optimized Bubble Sort (If you want to keep the basic algorithm) **Notes on optimization:** - **Early exit**: If no swaps, stop early (best-case O(n)). - **Avoid unnecessary work**: Don't recheck sorted tail. - **Tuple swap**: Pythonic, can be faster than three assignments. --- ### Recommendation - If you only care about speed and not the sorting algorithm: **Use Option 1**. - If you're required to use bubble sort or similar: **Use Option 2.** **Either will be vastly faster than your original code.** Your main slowness was due to the O(n²) inefficient bubble sort. Let me know if you need it adapted for e.g. descending order or for specific data types!
1 parent 4a68aa0 commit 65c7370

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

code_to_optimize/bubble_sort.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
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):
3+
n = len(arr)
4+
for i in range(n):
5+
swapped = False
6+
# Each pass can skip the last i elements, which are already sorted
7+
for j in range(n - i - 1):
58
if arr[j] > arr[j + 1]:
6-
temp = arr[j]
7-
arr[j] = arr[j + 1]
8-
arr[j + 1] = temp
9+
arr[j], arr[j + 1] = arr[j + 1], arr[j]
10+
swapped = True
11+
if not swapped:
12+
# If no swaps occurred, the array is already sorted
13+
break
914
print(f"result: {arr}")
1015
return arr

0 commit comments

Comments
 (0)