-
-
Notifications
You must be signed in to change notification settings - Fork 46.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
improvement to insertion_sort algorithm #9002
Labels
enhancement
This PR modified some existing files
Comments
using enumerate adds unnecessary extra conditions. 'for' loop along with two pointers for comparing and swapping is the most favorable. I think you should approach with indexes |
amirsoroush
added a commit
to amirsoroush/PythonAlgorithms
that referenced
this issue
Aug 21, 2023
amirsoroush
added a commit
to amirsoroush/PythonAlgorithms
that referenced
this issue
Aug 21, 2023
11 tasks
tianyizheng02
pushed a commit
that referenced
this issue
Aug 21, 2023
sedatguzelsemme
pushed a commit
to sedatguzelsemme/Python
that referenced
this issue
Sep 15, 2024
…thms#9005) * fixes TheAlgorithms#9002; improve insertion_sort algorithm * add type hints to sorts/insertion_sort.py
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Feature description
I was about to make a PR to improve the implementation of insertion_sort algorithm but since there might be multiple ways of doing so, I thought I should first ask your opinions.
These are the things that need improvements:
We unnecessarily create a whole new copy of the list:
enumerate(collection[1:])
.We can either use "indexes" to avoid this which is not very pythonic, or we can use the iterator of the list using
iter()
and throw away the first item usingnext()
. In second case we have to either check for empty list first or wrap it in a try-except block. I'll go with indexes if you ask. What do you think?I think a function should either mutate the list in-place and returns
None
, or it should create new sorted list without modifying the original list. Mutating the list and returning the mutated list is not what most developers expect to see. What do you think?We can safely remove
if insert_index != temp_index:
condition and unindent its body. Assigning an item to an index of a list is not costly. So it's one less line in general.The text was updated successfully, but these errors were encountered: