DEV Community


Posted on


Visualizing insertion Sort in python using pygame

This is the second part of my series... Visualizing Sorting algorithms in python.
In this second part, we are going to talk about insertion sort. This is a simple sorting algorithm that works like a deck of cards.

Now to the juicy part. Head per to your terminal and navigate to your desired directory.

cd Desktop && mkdir visuals && cd visuals

Once in the visuals directory, open vs code

code . 

Create and activate the virtual environment by

python3 -m virtualenv venv && source venv/bin/activate

Install pygame using pip

pip install pygame

Create a file named


Now to the juicer part... Implementing the fleshy part

import pygame
import random
import numpy as np
win = pygame.display.set_mode((800,800))
pygame.display.set_caption("Bubble sort")
x,y = 40,40
width = 20 

height = [ np.unique(random.randint(0,600)) for i in range(30)]

run = True 

def show(height):
    for i in range(len(height)):
        pygame.draw.rect(win,(74,192,200),(x + 30 * i,y,width,height[i]))

while run:
    execute = False
    keys = pygame.key.get_pressed()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    if keys[pygame.K_SPACE]:
        execute = True 
    if execute == False:
        for i in range(0,len(height)-1):
            while height[i] > height[i+1] and i >= 0:
                height[i],height[i+1] = height[i+1],height[i]
                i -= 1

I do hope that you have learnt a thing or two today. Will truly appreciate if you, yes you follow me on Github link
I will honestly appreciate code reviews and constructive criticism, Till next time...

Top comments (0)

50 CLI Tools You Can't Live Without

>> Check out this classic DEV post <<