Open In App

Bubble sort visualizer using PyGame

Last Updated : 30 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article we will see how we can visualize the bubble sort algorithm using PyGame i.e when the pygame application get started we can see the unsorted bars with different heights and when we click space bar key it started getting arranging in bubble sort manner i.e after every iteration maximum value element should come at last. Bubble Sort is a simple algorithm which is used to sort a given set of n elements provided in form of an array with n number of elements. Bubble Sort compares all the element one by one and sort them based on their values.

Implementation steps : 1. Create a main window 2. Fill the main window with black color 3. Create a method to show the list of bar with specific gap in between them 4. Get the keys input from the user 5. If space bar is pressed start the sorting process 6. Implement bubble sort algorithm on the list 7. After every internal iteration fill the screen with black color and call the show method to show the iterated list in the form of bar.

Below is the implementation 

Python3




# importing pygame
import pygame
 
pygame.init()
 
# setting window size
win = pygame.display.set_mode((500, 400))
 
# setting title to the window
pygame.display.set_caption("Bubble sort")
 
# initial position
x = 40
y = 40
 
# width of each bar
width = 20
 
# height of each bar (data to be sorted)
height = [200, 50, 130, 90, 250, 61, 110,
            88, 33, 80, 70, 159, 180, 20]
 
run = True
 
# method to show the list of height
def show(height):
 
    # loop to iterate each item of list
    for i in range(len(height)):
 
        # drawing each bar with respective gap
        pygame.draw.rect(win, (255, 0, 0), (x + 30 * i, y, width, height[i]))
 
# infinite loop
while run:
 
    # execute flag to start sorting
    execute = False
 
    # time delay
    pygame.time.delay(10)
 
    # getting keys pressed
    keys = pygame.key.get_pressed()
 
    # iterating events
    for event in pygame.event.get():
 
        # if event is to quit
        if event.type == pygame.QUIT:
 
            # making run = false so break the while loop
            run = False
 
    # if space bar is pressed
    if keys[pygame.K_SPACE]:
        # make execute flag to true
        execute = True
 
    # checking if execute flag is false
    if execute == False:
 
        # fill the window with black color
        win.fill((0, 0, 0))
 
        # call the height method to show the list items
        show(height)
 
        # update the window
        pygame.display.update()
 
    # if execute flag is true
    else:
 
        # start sorting using bubble sort technique
        for i in range(len(height) - 1):
 
            # after this iteration max element will come at last
            for j in range(len(height) - i - 1):
 
                # starting is greater than next element
                if height[j] > height[j + 1]:
 
                    # save it in temporary variable
                    # and swap them using temporary variable
                    t = height[j]
                    height[j] = height[j + 1]
                    height[j + 1] = t
 
                # fill the window with black color
                win.fill((0, 0, 0))
 
                # call show method to display the list items
                show(height)
 
                # create a time delay
                pygame.time.delay(50)
 
                # update the display
                pygame.display.update()
 
# exiting the main window
pygame.quit()


Output :



Previous Article
Next Article

Similar Reads

Selection sort visualizer using PyGame
In this article, we will see how to visualize Selection sort using a Python library PyGame. It is easy for the human brain to understand algorithms with the help of visualization. Selection sort is a simple and easy-to-understand algorithm that is used to sort elements of an array by dividing the array into two parts one sorted and the other unsort
3 min read
Adding Collisions Using pygame.Rect.colliderect in Pygame
Prerequisite: Drawing shapes in Pygame, Introduction to pygame In this article, we are going to use pygame.Rect.colliderect for adding collision in a shape using Pygame in Python. We can easily add collisions in Pygame shapes using the colliderect( ). For this, we are going to draw two rectangles then we will check if the rectangles are colliding o
3 min read
Sort an array using Bubble Sort without using loops
Given an array arr[] consisting of N integers, the task is to sort the given array by using Bubble Sort without using loops. Examples: Input: arr[] = {1, 3, 4, 2, 5}Output: 1 2 3 4 5 Input: arr[] = {1, 3, 4, 2}Output: 1 2 3 4 Approach: The idea to implement Bubble Sort without using loops is based on the following observations: The sorting algorith
9 min read
Visualizing Bubble sort using Python
Prerequisites: Introduction to Matplotlib, Introduction to PyQt5, Bubble Sort Learning any algorithm can be difficult, and since you are here at GeekforGeeks, you definitely love to understand and implement various algorithms. It is tough for every one of us to understand algorithms at the first go. We tend to understand those things more which are
3 min read
Visualizing Bubble Sort using Tkinter in Python
In this article, we will use the Python GUI Library Tkinter to visualize the Bubble Sort algorithm. Tkinter is a very easy to use and beginner-friendly GUI library that can be used to visualize the sorting algorithms.Here Bubble Sort Algorithm is visualized which works by repeatedly swapping the adjacent elements/values if they are in the wrong ord
5 min read
Get Second Largest Number in Python List Using Bubble Sort
Finding the second-largest number in a list is a common programming task that involves sorting the list in ascending order. Bubble sort is a simple sorting algorithm that can be used for this purpose. In this article, we will explore the logic behind finding the second largest number using bubble sort and provide a Python program to implement it. M
3 min read
Fibonacci Search Visualizer using PyQt5
In this article we will see how we can make a PyQt5 application which will visualize the exponential search algorithm. Fibonacci search technique is a method of searching a sorted array using a divide and conquer algorithm that narrows down possible locations with the aid of Fibonacci numbers.[1] Compared to binary search where the sorted array is
5 min read
Linear Search Visualizer using PyQt5
In this article we will see how we can make a PyQt5 application which will visualize the linear search algorithm. Linear search or sequential search is a method for finding an element within a list. It sequentially checks each element of the list until a match is found or the whole list has been searched. Gui implementation steps : 1. Create a list
5 min read
Interpolation Search visualizer using PyQt5
In this article we will see how we can make a PyQt5 application which will visualize the interpolation search algorithm.The Interpolation Search is an improvement over Binary Search for instances, where the values in a sorted array are uniformly distributed. Binary Search always goes to the middle element to check. On the other hand, interpolation
6 min read
Exponential Search Visualizer using PyQt5
In this article we will see how we can make a PyQt5 application which will visualize the Exponential search algorithm. Exponential search can also be used to search in bounded lists. Exponential search can even out-perform more traditional searches for bounded lists, such as binary search, when the element being searched for is near the beginning o
6 min read
Article Tags :
Practice Tags :