-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubble_sort.py
More file actions
136 lines (112 loc) · 2.88 KB
/
bubble_sort.py
File metadata and controls
136 lines (112 loc) · 2.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
"""
Animated bubble sort
"""
__author__ = "Ahmed Hassan"
__license__ = "MIT"
__email__ = "ahmedhassan@aims.ac.za"
import random
import sys
import time
import pygame
from utils import draw_array, animate_swap
pygame.init()
screen_width, screen_height = 1200, 500
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Bubble Sort Animation")
# Font
font = pygame.font.Font(None, 36)
BLACK = (0, 0, 0)
BLUE = (58, 148, 255)
LIGHT_BLUE = (170, 214, 255)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GOLDEN_YELLOW = (255, 215, 0)
GREEN = (50, 205, 50)
# Input array
num_elements = 10
array = [random.randint(1, 99) for _ in range(num_elements)]
# Best Case: array is already sorted
# Uncomment the line below
# array = sorted(array)
# Worst Case: array is reverse sorted
# Uncomment the line below
# array = sorted(array, reverse=True)
rect_width = screen_width // num_elements
rect_height = 100
# Place the array in the middle of the screen
y = (screen_height - rect_height) // 2
# Control animation speed
clock = pygame.time.Clock()
speed = 360 # frame rate
delay = 0.2 # seconds
def bubble_sort(array):
n = len(array)
while n >= 1:
k = 0
for i in range(1, n):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
draw_array(
array,
screen,
y,
rect_width,
rect_height,
clock,
speed,
font,
highlight_indexes=[i - 1, i],
)
time.sleep(delay)
if array[i - 1] > array[i]:
animate_swap(
array,
i - 1,
i,
y,
screen,
rect_width,
rect_height,
clock,
speed,
font,
)
draw_array(
array,
screen,
y,
rect_width,
rect_height,
clock,
speed,
font,
highlight_indexes=[i - 1, i],
highlight_color=GREEN,
)
time.sleep(delay)
k = i
n = k
draw_array(
array,
screen,
y,
rect_width,
rect_height,
clock,
speed,
font,
list(range(len(array))),
highlight_color=GREEN,
)
def main():
running = True
bubble_sort(array)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
if __name__ == "__main__":
main()