Skip to content

Commit 78afb3d

Browse files
⚡️ Speed up function sorter by 83%
Here’s a much faster rewritten version of your program. Your original implementation is a classic **bubble sort** (O(n²)) with redundant passes and repeated calls to `len(arr)`. The program can be made significantly faster by. - Using Python's built-in `sort()`, which uses Timsort (O(n log n)). - Alternatively, if you wish to keep the explicit algorithm, using an optimized Bubble Sort that stops when the list is already sorted, and reduces the inner loop length by each completed pass. - Reducing repeated attribute lookups (e.g., store `len(arr)` once). - Removing unnecessary data swaps (`temp`) by using Python tuple assignment. The **fastest** you can get is with the built-in sort, but if you must use your own loop (since you want the print statements to output the same way and avoid return value changes), here are both options. --- **Option 1: Fastest Built-in Sort** --- **Option 2: Optimized Bubble Sort (if custom algorithm is required)** --- **Explanation of the optimization:** - `arr.sort()` leverages Python's Timsort, which is much faster and memory-efficient for almost all practical purposes. - For the manual method, reducing passes and skipping redundant comparisons makes it much faster (`O(n²)` worst, `O(n)` best). - Early exit if no swaps (already sorted). - Reduced function overhead and Python list indexing looks. *Both options retain exactly the print outputs and function return of the original. Use Option 1 unless your requirements specifically forbid `sort()`.*
1 parent 2185af9 commit 78afb3d

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

code_to_optimize/bubble_sort.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
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+
# Reduce inner loop to skip already sorted tail
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] # Faster Pythonic swap
10+
swapped = True
11+
if not swapped:
12+
break # Stop if sorted
913
print(f"result: {arr}")
1014
return arr

0 commit comments

Comments
 (0)