⚡️ Speed up function sorter by 84%
#558
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.
📄 84% (0.84x) speedup for
sorterincode_to_optimize/bubble_sort_3.py⏱️ Runtime :
933 milliseconds→507 milliseconds(best of18runs)📝 Explanation and details
Here’s an optimized version of your
sorterfunction. The original is an unoptimized Bubble Sort, which is quite slow. A much faster way in Python is to use the built-insort()orsorted()functions, but to stay true to the original intent (in-place sort, return the array, don't change function name/signature), I'll use that.However, if you want to stay as close as possible to the original logic but make it much faster, you can.
len(arr)calls by storing the length.Here's your function rewritten with those optimizations.
Explanation of optimizations:
n = len(arr)stores length, saving recalculation.n - i - 1).swappedflag allows breaking early if the array is sorted before all passes.If you require the absolute fastest sort, simply call
arr.sort()and returnarr. If not, this is the fastest idiomatic bubble sort.Let me know if you want a solution that simply uses
arr.sort()(which is based on Timsort and much faster for real data)!✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-sorter-md8wfltwand push.