Last answered:

21 Dec 2023

Posted on:

15 Dec 2023

0

Alternative solution for insertion sort

This solution follows exactly the description of the algorithm in the video as I have understood it, so it is more intuitive for me. It seems to work. Is it correct?

def insertion_sort(my_list):
    i = 1
    while i < len(my_list):
        if my_list[i] < my_list[i-1]:
            # Insert the value into the left (sorted) list
            for left_i, left_v in enumerate(my_list[:i]):
                if my_list[i] < left_v:
                    to_insert = my_list.pop(i)
                    my_list = my_list[:left_i] + [to_insert] + my_list[left_i:]
        else:
            i += 1
    return my_list

 

1 answers ( 0 marked as helpful)
Instructor
Posted on:

21 Dec 2023

0

Hey Klim,


Thank you for sharing your implementation with the community.


The code you provide does modify the insertion sort algorithm slightly and increases its complexity (i.e., computation time). In a standard insertion sort, the list is sorted in-place, and elements are shifted rather than being popped and reinserted. Still, to answer your question, the code is correct and completes the task successfully.


Kind regards,

365 Hristina

Submit an answer