⚡️ Speed up function sorter by 121%
#724
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.
📄 121% (1.21x) speedup for
sorterincode_to_optimize/bubble_sort_3.py⏱️ Runtime :
843 milliseconds→381 milliseconds(best of19runs)📝 Explanation and details
The optimized bubble sort implements two key algorithmic improvements that significantly reduce unnecessary operations:
1. Early Exit Optimization: The code adds a
swappedflag to detect when the array becomes sorted during any pass. If no swaps occur in a complete pass, the array is already sorted and the algorithm terminates early. This is especially powerful for already-sorted or nearly-sorted data, as seen in the test results where sorted lists show dramatic speedups (99924% faster for large sorted lists).2. Reduced Inner Loop Range: The inner loop range changes from
range(len(arr) - 1)torange(len(arr) - 1 - i). After each outer loop iteration, the largest remaining element "bubbles up" to its correct position at the end, so there's no need to re-examine those already-sorted tail elements.Performance Impact: The line profiler shows the inner loop executes ~4.98M times vs ~14M times in the original (64% reduction). While the swapping operations remain identical (same number of swaps needed), the algorithm eliminates millions of redundant comparisons. The speedup is most pronounced on:
These optimizations maintain bubble sort's O(n²) worst-case complexity but achieve O(n) best-case performance when data is already sorted, making it much more practical for real-world scenarios where input data may have some existing order.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-sorter-mfcsokoaand push.