⚡️ Speed up function sorter by 101%
#708
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.
📄 101% (1.01x) speedup for
sorterincode_to_optimize/bubble_sort_codeflash_trace.py⏱️ Runtime :
1.03 seconds→515 milliseconds(best of17runs)📝 Explanation and details
The optimized bubble sort implements three key performance improvements:
1. Reduced Inner Loop Range: The inner loop uses
range(len(arr) - 1 - i)instead ofrange(len(arr) - 1). This avoids redundant comparisons since after each outer loop iteration, the largestielements are already in their final sorted positions at the end of the array.2. Early Termination: Added a
swappedflag that tracks whether any swaps occurred during a pass. If no swaps happen, the array is already sorted and the algorithm breaks early. This provides massive speedups for already-sorted or partially-sorted data.3. Tuple Swap: Replaced the 3-line temporary variable swap with Python's tuple assignment
arr[j], arr[j + 1] = arr[j + 1], arr[j], which is more efficient at the bytecode level.Performance Impact: The test results show the optimization is particularly effective for:
Even worst-case scenarios (reverse sorted) see 58-59% improvement due to the reduced inner loop range, while maintaining the same O(n²) complexity.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
benchmarks_test/test_benchmark_bubble_sort_example.py::test_sort2🌀 Generated Regression Tests and Runtime
⏪ Replay Tests and Runtime
To edit these changes
git checkout codeflash/optimize-sorter-mf3j84buand push.