Skip to content

Commit 61aee4b

Browse files
⚡️ Speed up function sorter by 87%
Certainly! Your code is a classic **bubble sort** implementation with two major performance issues. - It never checks if the array is already sorted in a pass, so it does the maximum number of iterations. - It redundantly computes `len(arr)` every inner-loop. - Bubble sort is inherently slow — but you require an in-place sort and the result must be the same, so we can improve with some key optimizations. ### Optimized Bubble Sort Improvements. 1. **Early exit:** Stop if no swaps occurred (array is sorted). 2. **Reduce inner loop range each time:** The last elements are already sorted after each pass. 3. **Direct tuple-swap:** Use Python's multiple assignment swap for speed. 4. **Pre-compute `len(arr)`:** Only compute once. Here is the **optimized version** preserving all your prints and output. ### Explanation of changes - **`swapped` check:** If no swaps in an outer pass, break for a big speed boost on nearly-sorted data. - **`range(n - i - 1)`:** Each pass pushes the next-largest value into place, so inner loop shortens. - **Tuple swap:** Faster than three assignments. - **No unnecessary calls to `len()` in loop.** This is the fastest bubble-sort possible without changing the algorithm (still in-place, correct result). **If you want even faster code, and are allowed to use Python's built-in sort**, you could simply use `arr.sort()`, but as per your request, this implements only the algorithmic optimization of what you already have.
1 parent e17d0f7 commit 61aee4b

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

code_to_optimize/bubble_sort.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
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+
for j in range(n - i - 1):
57
if arr[j] > arr[j + 1]:
6-
temp = arr[j]
7-
arr[j] = arr[j + 1]
8-
arr[j + 1] = temp
8+
arr[j], arr[j + 1] = arr[j + 1], arr[j] # faster swap
9+
swapped = True
10+
if not swapped:
11+
break # array is sorted
912
print(f"result: {arr}")
1013
return arr

0 commit comments

Comments
 (0)