⚡️ Speed up function sorter by 105%
#721
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.
📄 105% (1.05x) speedup for
sorterinapp/sort.py⏱️ Runtime :
840 milliseconds→409 milliseconds(best of21runs)📝 Explanation and details
The optimized bubble sort implementation achieves a 2x speedup through three key algorithmic improvements:
1. Reduced inner loop bounds: Changed
range(len(arr) - 1)torange(n - i - 1). Since each outer pass bubbles the largest remaining element to its final position, the inner loop can skip checking the already-sorted tail. This reduces iterations from ~13M to ~5M in the profiler results.2. Early termination: Added a
swappedflag that breaks the outer loop when no swaps occur in a pass, indicating the array is sorted. This optimization provides massive gains on already-sorted data - test results show 44,162% speedup on large sorted lists (51ms → 115μs) and 42,598% speedup on identical elements.3. Tuple unpacking for swaps: Replaced the 3-line temporary variable swap with
arr[j], arr[j + 1] = arr[j + 1], arr[j], which is more efficient in Python and reduces the swap overhead from ~24% to ~20% of total runtime.The optimizations are particularly effective for:
The early termination feature makes this bubble sort adaptive to input characteristics while maintaining the same O(n²) worst-case complexity.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-sorter-mfcr7qu7and push.