Bubble sort visualizer using PyGame (original) (raw)
Last Updated : 25 Apr, 2025
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
import
pygame
pygame.init()
win
=
pygame.display.set_mode((
500
,
400
))
pygame.display.set_caption("Bubble sort")
x
=
40
y
=
40
width
=
20
height
=
[
200
,
50
,
130
,
90
,
250
,
61
,
110
,
`` 88
,
33
,
80
,
70
,
159
,
180
,
20
]
run
=
True
def
show(height):
`` for
i
in
range
(
len
(height)):
`` pygame.draw.rect(win, (
255
,
0
,
0
), (x
+
30
*
i, y, width, height[i]))
while
run:
`` execute
=
False
`` pygame.time.delay(
10
)
`` 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
:
`` win.fill((
0
,
0
,
0
))
`` show(height)
`` pygame.display.update()
`` 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()
pygame.quit()
Output :