Insertion Sort

In Insertion Sort, every element in the list is compared with previous elements in the list and placed in the right position.

consider a list [5, 2, 4, 6, 1, 3]

second element is compared with the first, let us assume we have to arrange the list in ascending order.

process: starting from second element which is compared to its previous elements and repeated.

Source Code in python

##insertion sort ##

def insertion(list1):
    for j in range(1,len(list1)):
        key=list1[j]
        i=j-1
        while i>=0 and list1[i]>key:
            list1[i+1]=list1[i]
            i=i-1
        list1[i+1]=key
        print list1

pass the list to the function while running the code.

Output:

[2, 5, 4, 6, 1, 3]
[2, 4, 5, 6, 1, 3]
[2, 4, 5, 6, 1, 3]
[1, 2, 4, 5, 6, 3]
[1, 2, 3, 4, 5, 6]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s