Skip to main content

Command Palette

Search for a command to run...

Insertion Sort

Updated
1 min readView as Markdown
Insertion Sort
A

I am a Tech enthusiast interested to learn new things from everyone and post my learning in public.

On a very basic level, an insertion sort algorithm contains the logic of shifting around and inserting elements to sort an unordered list of any size. The way that it goes about inserting elements, however, is what makes insertion sort so very interesting!

def insertion_sort(lst):

    for i in range(1, len(lst)):
        key = lst[i]
        j = i - 1
        while j >= 0 and key < lst[j]:
            lst[j + 1] = lst[j]
            j -= 1
            lst[j + 1] = key

Here are the input and output:

lst = [7,4,9,2,6,3]
insertionsort(lst)
print('Sorted %s'  %lst) # sorted [2, 3, 4, 6, 7, 9]

More from this blog

D

DEVS-OnThe-PUB

18 posts

The Content here will surely impact you, even if its in a small way. A place where Things are without bias...