There are various types of sorting algorithms out there and sometimes it becomes very difficult to understand their internal working without visualization. Hence I decided to visualize these sorting algorithms in python with the help of matplotlib.animations library.

NOTE:- In this article, we will also compute the number of operations performed and will be able to see the time complexity of the sorting algorithm.

As our purpose is to only visualize the sorting algorithms hence I will be using the merge sort for a demonstration but you should implement the rest of them in order to understand the differences among them.

Before we start coding, you must have python 3.3 or above installed because I have used the yield from feature or generator.

Let’s Start:-

Firstly you need to import the given libraries. We have used the random module in order to generate a random array of numbers to be sorted. The matplotlib pyplot and animation modules will be used to animate the sorting algorithm.

import random
import matplotlib.pyplot as plt
import matplotlib.animation as anim

Below the given swap function will be used to swap the elements in the given array. Defining a separate function is useful as it will be used exhaustively throughout different algorithms.

def swap(A, i, j):
    a = A[j]
    A[j] = A[i]
    A[i] = a
    ## also in python A[i],A[j]=A[j],A[i]

We have used Merge Sort to demonstrate this visualization because this is the most popular and one of the best sorting algorithms out there. Merge sort follows Divide and Conquer technique for sorting. It divides the array into two subarrays and each of these is sorted by calling the merge sort recursively on them. Our main focus is to visualize the algorithm hence I will not explain the working of it. The following code shows the merge sort. In order to get the intuition on how it works, one can follow this video on youtube jenny’s lecture.

def merge_sort(arr,lb,ub):
    if(ub<=lb):
        return
    elif(lb<ub):
        mid =(lb+ub)//2
        yield from merge_sort(arr,lb,mid)
        yield from merge_sort(arr,mid+1,ub)
        yield from merge(arr,lb,mid,ub)
        yield arr
def merge(arr,lb,mid,ub):
    new = []
    i = lb
    j = mid+1
    while(i<=mid and j<=ub):
        if(arr[i]<arr[j]):
            new.append(arr[i])
            i+=1
        else:
            new.append(arr[j])
            j+=1
    if(i>mid):
        while(j<=ub):
            new.append(arr[j])
            j+=1
    else:
        while(i<=mid):
            new.append(arr[i])
            i+=1
    for i,val in enumerate(new):
        arr[lb+i] = val
        yield arr

#python #programming #merge-sort #sorting-algorithms #visualization

Visualize an Interesting Sorting Algorithms With Python
3.30 GEEK