Insertion Sort Algorithm in Python

In this source code example, we will write a code to implement the Insertion Sort algorithm in Python.

This algorithm sorts a collection by comparing adjacent elements. When it finds that order is not respected, it moves the element compared backward until the order is correct. It then goes back directly to the element's initial position resuming forward comparison.

Insertion Sort Algorithm in Python

In this Python program, we will take input from the User or console and print the result to the output:
def insertion_sort(collection: list) -> list:
    for insert_index, insert_value in enumerate(collection[1:]):
        temp_index = insert_index
        while insert_index >= 0 and insert_value < collection[insert_index]:
            collection[insert_index + 1] = collection[insert_index]
            insert_index -= 1
        if insert_index != temp_index:
            collection[insert_index + 1] = insert_value
    return collection

if __name__ == "__main__":
    user_input = input("Enter numbers separated by a comma:\n").strip()
    unsorted = [int(item) for item in user_input.split(",")]
    print(f"{insertion_sort(unsorted) = }")


Enter numbers separated by a comma:
insertion_sort(unsorted) = [1, 2, 3, 5, 10, 15, 20]

Related Algorithms in Python

Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course