Skip to content

improvement to insertion_sort algorithm #9002

Closed
@amirsoroush

Description

@amirsoroush

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:

  1. 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 using next(). 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?

  2. 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?

  3. 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementThis PR modified some existing files

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions