Skip to content

Commit 6647e3b

Browse files
⚡️ Speed up function sorter by 223,402%
Here's an optimized version of your code. ### Major improvements. - **Use Python built-in sort:** The original code is an unoptimized bubble sort (`O(n^2)`), while Python's built-in `sort` runs in `O(n log n)` and is highly optimized in C. - **If you must keep the in-place sorting and returning of `arr`, just use `arr.sort()`.** - **All variable swapping is handled internally by Python efficiently.** #### If you want to keep a manual fast sort (like quicksort), consider. ### Why this is faster. - Removes unnecessary Python for-loops and variable swaps. - Built-ins leverage C speed and tim-sort algorithm. - **Behavior is identical:** sorts `arr` in-place and returns it. --- If you need a manual algorithm for educational purposes (not recommended for production), I can provide a fast implementation (e.g., using quicksort or heapsort), but for 99% of use cases, the above is best for speed and memory!
1 parent 2a576cb commit 6647e3b

File tree

1 file changed

+2
-6
lines changed

1 file changed

+2
-6
lines changed

code_to_optimize/bubble_sort_3.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,4 @@
11
def sorter(arr):
2-
for i in range(len(arr)):
3-
for j in range(len(arr) - 1):
4-
if arr[j] > arr[j + 1]:
5-
temp = arr[j]
6-
arr[j] = arr[j + 1]
7-
arr[j + 1] = temp
2+
# Use built-in sorted which is highly efficient for any input
3+
arr.sort()
84
return arr

0 commit comments

Comments
 (0)