⚡️ Speed up function sorter
by 165%
#725
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 165% (1.65x) speedup for
sorter
insrc/data/sort.py
⏱️ Runtime :
1.19 seconds
→450 milliseconds
(best of18
runs)📝 Explanation and details
The optimized code implements three key improvements to the bubble sort algorithm:
1. Early termination with swapped flag: Adds a
swapped
boolean that tracks if any swaps occurred during a pass. If no swaps happen, the list is already sorted and the algorithm exits early. This is especially powerful for already-sorted or nearly-sorted data.2. Reduced inner loop iterations: Changes the inner loop from
range(len(arr) - 1)
torange(n - i - 1)
. After each pass, the largesti
elements are guaranteed to be in their final positions, so we can skip checking them.3. Optimized swapping: Replaces the three-line temporary variable swap with Python's tuple unpacking
arr[j], arr[j + 1] = arr[j + 1], arr[j]
, which is more efficient at the bytecode level.Why this leads to speedup: The early termination provides massive gains for sorted/nearly-sorted data (40,000%+ faster on large sorted lists), while the reduced loop bounds decrease total comparisons by roughly half. Even for worst-case scenarios like reverse-sorted lists, the optimizations still provide 56-83% speedup due to fewer loop iterations and efficient swapping.
Test case performance: The optimization excels on already-sorted data, identical elements, and partially-sorted lists, while maintaining good performance on random data. Small lists see minimal improvement due to optimization overhead, but large datasets benefit significantly from the algorithmic improvements.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-sorter-mfcxvice
and push.