⚡️ Speed up sorter()
by 4225716.95 in code_to_optimize/bubble_sort_3.py
#27
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.
📄
sorter()
incode_to_optimize/bubble_sort_3.py
📈 Performance went up by
4225716.95
(42257.17
faster)⏱️ Runtime went down from
1241206.96μs
to29.37μs
Explanation and details
(click to show)
Your current function is using Bubble sort which is a simple comparison-based sort but it's not very efficient for larger lists. It's time complexity is O(n^2), which means it's going to slow down significantly for larger lists.
A better option for sorting lists in Python is to use Python's built-in
sort()
function or thesorted()
function, which is implemented with a variant of MergeSort (a much more efficient sorting algorithm) by the Python developers.The optimized code would look something like this:
Note that
sort()
sorts the list in-place, i.e., it doesn't create a new list. If you want to create a new sorted list without changing the original one, usesorted(arr)
instead.One more thing to note is: If the input array is intended to be sorted in reverse order, you can use
arr.sort(reverse=True)
.Correctness verification
The new optimized code was tested for correctness. The results are listed below.
✅ 15 Passed − ⚙️ Existing Unit Tests
✅ 0 Passed − 🎨 Inspired Regression Tests
✅ 15 Passed − 🌀 Generated Regression Tests
(click to show generated tests)