⚡️ Speed up function sorter by 108%
#722
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.
📄 108% (1.08x) speedup for
sorterinsrc/app/sort.py⏱️ Runtime :
910 milliseconds→437 milliseconds(best of19runs)📝 Explanation and details
The optimized code implements three key optimizations to the bubble sort algorithm that significantly improve performance:
1. Reduced Inner Loop Range: Instead of always iterating through
len(arr) - 1elements, the inner loop now usesrange(n - 1 - i). This leverages the fact that after each outer loop pass, the largest element "bubbles up" to its correct position at the end, so we don't need to check those already-sorted elements again. This reduces comparisons from ~14M to ~5.4M hits.2. Early Exit with Swap Detection: A
swappedflag tracks whether any swaps occurred during a pass. If no swaps happen, the array is already sorted and the algorithm exits early withbreak. This is particularly effective for already-sorted or nearly-sorted data.3. Tuple Swap: Replaced 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 and eliminates one variable assignment per swap.Performance Impact: The optimizations show dramatic improvements especially for:
The 108% overall speedup comes from the combination of fewer loop iterations (reduced from 14M to 5.4M inner loop hits) and intelligent early termination for favorable input patterns.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-sorter-mfcrffqgand push.