Skip to content

Commit 9192615

Browse files
⚡️ Speed up function sorter by 84%
Here’s an optimized version of your `sorter` function. The original is an unoptimized Bubble Sort, which is quite slow. A **much faster way in Python** is to use the built-in `sort()` or `sorted()` functions, but to stay true to the original intent (in-place sort, return the array, don't change function name/signature), I'll use that. However, if you want to **stay as close as possible to the original logic but make it much faster**, you can. 1. Avoid repeated `len(arr)` calls by storing the length. 2. Notice that with each pass, the largest remaining item is at the end, so the inner loop can shrink. 3. Add early exit if no swaps occur (optimization for already nearly-sorted input). Here's your function rewritten with those optimizations. **Explanation of optimizations:** - `n = len(arr)` stores length, saving recalculation. - Inner loop does not consider elements already sorted at the end (`n - i - 1`). - `swapped` flag allows breaking early if the array is sorted before all passes. - Tuple swap is slightly faster and cleaner than using a temp variable. If you require the absolute fastest sort, simply call `arr.sort()` and return `arr`. If not, this is the fastest idiomatic bubble sort. Let me know if you want a solution that simply uses `arr.sort()` (which is based on Timsort and much faster for real data)!
1 parent 5aab3b8 commit 9192615

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

code_to_optimize/bubble_sort_3.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
def sorter(arr):
2-
for i in range(len(arr)):
3-
for j in range(len(arr) - 1):
2+
n = len(arr)
3+
for i in range(n):
4+
swapped = False
5+
for j in range(n - i - 1):
46
if arr[j] > arr[j + 1]:
5-
temp = arr[j]
6-
arr[j] = arr[j + 1]
7-
arr[j + 1] = temp
7+
arr[j], arr[j + 1] = arr[j + 1], arr[j]
8+
swapped = True
9+
if not swapped:
10+
break
811
return arr

0 commit comments

Comments
 (0)