⚡️ Speed up sorter()
by 4211531.56 in PR #1 (new-sorter
)
#3
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.
⚡️ This pull request contains optimizations for PR #1
If you approve this dependent PR, these changes will be merged into the original PR branch
new-sorter
.📄
sorter()
incode_to_optimize/bubble_sort.py
📈 Performance went up by
4211531.56
(42115.32
faster)⏱️ Runtime went down from
1070554.63μs
to25.42μs
Explanation and details
(click to show)
The function you provided, sorter, is already using Python's built-in sort function which has a time complexity of O(n log n), where n is a number of elements in the array. This is the fastest achievable sorting complexity for comparison-based sorts.
However, if you want to achieve a marginal speed increase, writing this in-place might help.
Here's an alternative version using list comprehension. Although this does not improve the time complexity, it gives a Pythonic touch:
Again, this command returns a new sorted list and does not modify the original list. If you want to sort the list in-place, you only have the original function:
Please note that sorting time complexity cannot be improved further than O(n log n) using comparison-based sorting algorithms. To really optimize this function, you would need a guarantee about the content of your data, for example, if your array only contained integers in a particular range, then you could use counting sort or radix sort, which can have a time complexity of O(n).
Correctness verification
The new optimized code was tested for correctness. The results are listed below.
🔘 (none found) − ⚙️ Existing Unit Tests
✅ 3 Passed − 🌀 Generated Regression Tests
(click to show generated tests)
undefined