,

Learn Bubble Sort Algorithm Visually with PyGame in Python

Bubble Sort Algorithm, In this article, we’ll explore how to visualize the bubble sort algorithm using PyGame. When the PyGame application starts, you’ll see unsorted bars of varying heights. Pressing the space bar will initiate the sorting process, where the bars will arrange themselves in a bubble sort manner, with the largest element moving to the end after each iteration. Bubble Sort is a simple algorithm used to sort an array of n elements by comparing and swapping adjacent elements based on their values.

Implementation steps For Bubble Sort Algorithm:

  1. Create the main window.
  2. Fill the main window with a black background.
  3. Create a method to display the bars with specific gaps between them.
  4. Capture user input.
  5. Start the sorting process when the space bar is pressed.
  6. Implement the bubble sort algorithm on the list.
  7. After each internal iteration, refill the screen with black and call the display method to show the updated list of bars.

Let’s get started with the code. Copy the code below and paste it in your code editor and see the output and watch the explanation below

# 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:

Explanation of the Code:

Importing Pygame:

import pygame

This imports the pygame library, which is used for creating games and multimedia applications.

Initialize Pygame:

pygame.init()

This initializes all the imported Pygame modules.

Setting Window Size:

win = pygame.display.set_mode((500, 400))

This creates a window of size 500×400 pixels.

Setting Window Title:

pygame.display.set_caption("Bubble sort")

This sets the title of the window to “Bubble sort”.

Initial Position and Dimensions:

x = 40
y = 40
width = 20

x and y are the initial coordinates for drawing the bars.width is the width of each bar.

Height of Each Bar (Data to be Sorted):

height = [200, 50, 130, 90, 250, 61, 110, 88, 33, 80, 70, 159, 180, 20]

This list contains the heights of the bars that need to be sorted.

Running the Application:

run = True

Method to Show the List of Heights:

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

This method draws the bars on the window with a gap of 30 pixels between each bar.

Main Loop:

while run:

Execute Flag and Time Delay:

execute = False
pygame.time.delay(10)

Getting Keys Pressed:

keys = pygame.key.get_pressed()

Iterating Through Events:

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        run = False

Checking if Space Bar is Pressed:

if keys[pygame.K_SPACE]:
    execute = True

Display Initial Heights if Execute Flag is False:

if execute == False:
    win.fill((0, 0, 0))
    show(height)
    pygame.display.update()

Bubble Sort Algorithm if Execute Flag is True:

else:
    for i in range(len(height) - 1):
        for j in range(len(height) - i - 1):
            if height[j] > height[j + 1]:
                t = height[j]
                height[j] = height[j + 1]
                height[j + 1] = t

            win.fill((0, 0, 0))
            show(height)
            pygame.time.delay(50)
            pygame.display.update()

Exiting the Application:

pygame.quit()

This code sets up a simple graphical application using Pygame that visualizes the bubble sort algorithm. It displays a series of bars representing the data to be sorted. When the space bar is pressed, the application starts sorting the bars using the bubble sort algorithm, visually demonstrating each swap in real-time.

Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>