Skip to content

Commit 23ebc7c

Browse files
⚡️ Speed up function sorter by 93,340%
The optimized code replaces a manual O(n²) bubble sort implementation with Python's built-in `arr.sort()` method, which uses the highly optimized Timsort algorithm (O(n log n)). **Key changes:** - Eliminated nested loops and manual element swapping with a single `arr.sort()` call - Reduced algorithmic complexity from O(n²) to O(n log n) - Leverages Python's C-implemented sorting which is significantly faster than Python loops **Why it's faster:** The original bubble sort performs excessive comparisons and swaps. For a 1000-element list, bubble sort makes ~500,000 operations while Timsort makes ~10,000. The built-in sort is also implemented in optimized C code rather than interpreted Python loops. **Performance characteristics:** - Small lists (≤10 elements): 200-400% faster due to reduced overhead - Large sorted lists: 900,000%+ faster since Timsort detects sorted runs and operates in O(n) time - Large random/reverse lists: 70,000-1,500,000%+ faster due to superior algorithmic complexity - Maintains identical behavior: in-place sorting with the same return value The optimization is universally beneficial across all test cases, with dramatic improvements on larger datasets where the O(n²) vs O(n log n) complexity difference becomes pronounced.
1 parent a474c22 commit 23ebc7c

File tree

1 file changed

+1
-6
lines changed

1 file changed

+1
-6
lines changed

code_to_optimize/bubble_sort_3.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,3 @@
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+
arr.sort()
83
return arr

0 commit comments

Comments
 (0)