Algorithms

Insertion Sort Algorithm (Python Code)

Algorithm: Insertion Sort

Insertion sort works by taking one item at a time and finding a more suitable location for it. This iteration continues until there is no element to sort.

STEP BY STEP

Insertion Sort in action

Insertion sort is a very simple and basic algorithm and it performs relatively better in comparison to bubble sort and selection sort algorithms.

However, it’s not very efficient in general and so it won’t be suitable for large datasets. 

You can see an illustrated scheme showing how insertion sort algorithm proceeds step by step below.

INSERTION SORT ALGORITHM CODE IN PYTHON

def insertionsort(A):

    for i in range(1, len(A)):
        j = i
        while j > 0 and A[j] < A[j - 1]:
            swap(A, j, j - 1)
            j -= 1
            yield A
            
def swap(A, i, j):
    """Helper function to swap elements i and j of list A."""

    if i != j:
        A[i], A[j] = A[j], A[i]            
            

Matplotlib has a great class called animation which can be used to generate animations and live charts as below:

INSERTION SORT ALGORITHM VISUALIZATION

Visualization of Insertion Sort Algorithm in action (25 items)

Using Python’s animation class and FuncAnimation method you can visualize your sorting algorithm as it sorts a random data you throw at it.

This can be achieved by taking advantage of generators concept in your algorithm and using that iterable generator to create a graph with FuncAnimation. It might seem more complicated that it actually is so feel free to work on the code below.

The code is a simplified version that was originally published in Najam Syed’s blog here.

if __name__ == "__main__":

    N = 25
    A = [x + 1 for x in range(N)]
    random.seed(time.time())
    random.shuffle(A)
    generator = insertionsort(A)

    figure, ax = plt.subplots(figsize=(19,15))
    bar_rects = ax.bar(range(len(A)), A, width=0.3, align="edge", color="green")

    
    iteration = [0]
    def update_figure(A, rects, iteration):
        for rect, val in zip(rects, A):
            rect.set_height(val)
        iteration[0] += 1

        
    anim = animation.FuncAnimation(figure, func=update_figure,
        fargs=(bar_rects, iteration), frames=generator, interval=100,
        repeat=False)
    plt.show()
Collection sorted with Insertion Sort Algorithm
Usag1r

Share
Published by
Usag1r

Recent Posts

Benefits of Bokeh over Python visualization libraries like Seaborn, Matplotlib & Plotly

ContentsIntroductionBokeh vs Seaborn & MatplotlibBokeh vs PlotlySummary Introduction As computer science activity booms, you might…

12 months ago

History of Speech-to-Text AI models

History of Speech-to-Text Models​ & Current Infrastructure As speech technology continues to advance, so too…

1 year ago

Advanced Level Python Tips & Tricks

Python Tips & Tricks (Part III) Advanced Level HolyPython.com Here are more Python tips about…

1 year ago

Intermediate Level Python Tips & Tricks

Python Tips & Tricks (Part II) Intermediate Level HolyPython.com The list continues with slightly more…

1 year ago

When is Python 4 Coming Out?

Almost 15 years after the release of Python 3 many people are wondering when Python…

2 years ago

How to Create an app with a 3D model using VIKTOR

Introduction We are going to need smart engineering solutions to solve our planet's problems (and…

2 years ago