-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
732 lines (592 loc) · 26.7 KB
/
main.py
File metadata and controls
732 lines (592 loc) · 26.7 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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
import pygame
import random
import math
import time
from typing import Generator, Tuple, Dict, List, Any
from dataclasses import dataclass
from enum import Enum
pygame.init()
class SortingState(Enum):
IDLE = "idle"
SORTING = "sorting"
COMPLETED = "completed"
class Theme(Enum):
DARK = "dark"
LIGHT = "light"
NEON = "neon"
@dataclass
class ColorScheme:
background: Tuple[int, int, int]
primary: Tuple[int, int, int]
secondary: Tuple[int, int, int]
accent: Tuple[int, int, int]
text: Tuple[int, int, int]
comparing: Tuple[int, int, int]
swapping: Tuple[int, int, int]
sorted: Tuple[int, int, int]
current: Tuple[int, int, int]
@classmethod
def get_theme(cls, theme: Theme) -> 'ColorScheme':
themes = {
Theme.DARK: cls(
background=(30, 30, 30),
primary=(70, 70, 70),
secondary=(100, 100, 100),
accent=(130, 130, 130),
text=(255, 255, 255),
comparing=(255, 165, 0),
swapping=(255, 69, 0),
sorted=(50, 205, 50),
current=(138, 43, 226)
),
Theme.LIGHT: cls(
background=(245, 245, 245),
primary=(200, 200, 200),
secondary=(170, 170, 170),
accent=(140, 140, 140),
text=(50, 50, 50),
comparing=(255, 140, 0),
swapping=(255, 69, 0),
sorted=(34, 139, 34),
current=(138, 43, 226)
),
Theme.NEON: cls(
background=(15, 15, 15),
primary=(0, 255, 255),
secondary=(255, 0, 255),
accent=(255, 255, 0),
text=(255, 255, 255),
comparing=(255, 20, 147),
swapping=(255, 69, 0),
sorted=(50, 255, 50),
current=(138, 43, 226)
)
}
return themes[theme]
class SortingStats:
def __init__(self):
self.reset()
def reset(self):
self.comparisons = 0
self.swaps = 0
self.start_time = None
self.end_time = None
self.array_accesses = 0
def start_sorting(self):
self.reset()
self.start_time = time.time()
def end_sorting(self):
self.end_time = time.time()
def get_elapsed_time(self) -> float:
if self.start_time is None:
return 0.0
end = self.end_time if self.end_time else time.time()
return end - self.start_time
class DrawInformation:
def __init__(self, width: int, height: int, lst: List[int], theme: Theme = Theme.DARK):
self.width = width
self.height = height
self.theme = theme
self.colors = ColorScheme.get_theme(theme)
# Enhanced fonts
self.small_font = pygame.font.Font(None, 24)
self.font = pygame.font.Font(None, 32)
self.large_font = pygame.font.Font(None, 48)
self.title_font = pygame.font.Font(None, 56)
# Layout constants
self.side_pad = 120
self.top_pad = 200
self.bottom_pad = 80
self.stats_height = 100
self.window = pygame.display.set_mode((width, height))
pygame.display.set_caption("Advanced Sorting Algorithm Visualizer")
self.stats = SortingStats()
self.state = SortingState.IDLE
self.set_list(lst)
def set_list(self, lst: List[int]):
self.lst = lst[:]
self.original_lst = lst[:]
self.min_val = min(lst)
self.max_val = max(lst)
available_width = self.width - self.side_pad
available_height = self.height - self.top_pad - self.bottom_pad - self.stats_height
self.block_width = max(2, available_width // len(lst))
self.block_height = available_height / (self.max_val - self.min_val) if self.max_val != self.min_val else 1
self.start_x = self.side_pad // 2
# Calculate optimal spacing
self.spacing = max(1, (available_width - len(lst) * self.block_width) // len(lst))
def cycle_theme(self):
themes = list(Theme)
current_index = themes.index(self.theme)
self.theme = themes[(current_index + 1) % len(themes)]
self.colors = ColorScheme.get_theme(self.theme)
def draw_ui(draw_info: DrawInformation, algo_name: str, ascending: bool, speed: int):
"""Draw the modern UI with enhanced graphics and information."""
draw_info.window.fill(draw_info.colors.background)
# Title with gradient effect
title_text = f"{algo_name}"
title_surface = draw_info.title_font.render(title_text, True, draw_info.colors.text)
title_rect = title_surface.get_rect(center=(draw_info.width // 2, 40))
draw_info.window.blit(title_surface, title_rect)
# Sort direction indicator
direction_text = f"{'▲ Ascending' if ascending else '▼ Descending'}"
direction_surface = draw_info.font.render(direction_text, True, draw_info.colors.accent)
direction_rect = direction_surface.get_rect(center=(draw_info.width // 2, 80))
draw_info.window.blit(direction_surface, direction_rect)
# Control instructions with better formatting
controls = [
"R - Reset | SPACE - Start/Pause | A/D - Direction | T - Theme",
"1-Bubble | 2-Insertion | 3-Selection | 4-Merge | 5-Quick | 6-Heap",
"↑/↓ - Speed | S - Step Mode | ESC - Exit"
]
for i, control in enumerate(controls):
text_surface = draw_info.small_font.render(control, True, draw_info.colors.text)
text_rect = text_surface.get_rect(center=(draw_info.width // 2, 110 + i * 25))
draw_info.window.blit(text_surface, text_rect)
# Speed indicator
speed_text = f"Speed: {speed}/10"
speed_surface = draw_info.font.render(speed_text, True, draw_info.colors.accent)
draw_info.window.blit(speed_surface, (20, 20))
# Theme indicator
theme_text = f"Theme: {draw_info.theme.value.title()}"
theme_surface = draw_info.font.render(theme_text, True, draw_info.colors.accent)
draw_info.window.blit(theme_surface, (draw_info.width - 200, 20))
def draw_stats(draw_info: DrawInformation):
"""Draw sorting statistics."""
stats_y = draw_info.height - draw_info.stats_height + 10
# Background for stats
stats_rect = pygame.Rect(0, stats_y - 10, draw_info.width, draw_info.stats_height)
pygame.draw.rect(draw_info.window, draw_info.colors.primary, stats_rect)
pygame.draw.rect(draw_info.window, draw_info.colors.accent, stats_rect, 2)
# Statistics
stats_text = [
f"Comparisons: {draw_info.stats.comparisons}",
f"Swaps: {draw_info.stats.swaps}",
f"Array Access: {draw_info.stats.array_accesses}",
f"Time: {draw_info.stats.get_elapsed_time():.3f}s"
]
for i, stat in enumerate(stats_text):
text_surface = draw_info.font.render(stat, True, draw_info.colors.text)
x = 20 + i * 200
draw_info.window.blit(text_surface, (x, stats_y + 10))
def draw_array(draw_info: DrawInformation, color_positions: Dict[int, Tuple[int, int, int]] = None,
clear_bg: bool = False):
"""Draw the array with enhanced visual effects."""
if color_positions is None:
color_positions = {}
lst = draw_info.lst
if clear_bg:
clear_rect = (
draw_info.side_pad // 2,
draw_info.top_pad,
draw_info.width - draw_info.side_pad,
draw_info.height - draw_info.top_pad - draw_info.bottom_pad - draw_info.stats_height
)
pygame.draw.rect(draw_info.window, draw_info.colors.background, clear_rect)
for i, val in enumerate(lst):
x = draw_info.start_x + i * (draw_info.block_width + draw_info.spacing)
height = max(5, int((val - draw_info.min_val) * draw_info.block_height))
y = draw_info.height - draw_info.bottom_pad - draw_info.stats_height - height
# Enhanced gradient coloring
if i in color_positions:
color = color_positions[i]
else:
# Create gradient based on value
ratio = (val - draw_info.min_val) / (draw_info.max_val - draw_info.min_val) if draw_info.max_val != draw_info.min_val else 0
if draw_info.theme == Theme.NEON:
color = (
int(draw_info.colors.primary[0] * (1 - ratio) + draw_info.colors.secondary[0] * ratio),
int(draw_info.colors.primary[1] * (1 - ratio) + draw_info.colors.secondary[1] * ratio),
int(draw_info.colors.primary[2] * (1 - ratio) + draw_info.colors.secondary[2] * ratio)
)
else:
color = (
int(draw_info.colors.primary[0] * (1 - ratio) + draw_info.colors.accent[0] * ratio),
int(draw_info.colors.primary[1] * (1 - ratio) + draw_info.colors.accent[1] * ratio),
int(draw_info.colors.primary[2] * (1 - ratio) + draw_info.colors.accent[2] * ratio)
)
# Draw bar with border
pygame.draw.rect(draw_info.window, color, (x, y, draw_info.block_width, height))
pygame.draw.rect(draw_info.window, draw_info.colors.text, (x, y, draw_info.block_width, height), 1)
# Add value labels for smaller arrays
if len(lst) <= 20:
text_surface = draw_info.small_font.render(str(val), True, draw_info.colors.text)
text_rect = text_surface.get_rect(center=(x + draw_info.block_width // 2, y - 15))
draw_info.window.blit(text_surface, text_rect)
if clear_bg:
pygame.display.update()
def draw_complete(draw_info: DrawInformation, algo_name: str, ascending: bool, speed: int):
"""Draw the complete interface."""
draw_ui(draw_info, algo_name, ascending, speed)
draw_array(draw_info)
draw_stats(draw_info)
pygame.display.update()
def generate_list(n: int, min_val: int, max_val: int, distribution: str = "random") -> List[int]:
"""Generate different types of lists for testing."""
if distribution == "random":
return [random.randint(min_val, max_val) for _ in range(n)]
elif distribution == "sorted":
return list(range(min_val, min_val + n))
elif distribution == "reverse":
return list(range(min_val + n - 1, min_val - 1, -1))
elif distribution == "nearly_sorted":
lst = list(range(min_val, min_val + n))
# Shuffle a few elements
for _ in range(n // 10):
i, j = random.randint(0, n-1), random.randint(0, n-1)
lst[i], lst[j] = lst[j], lst[i]
return lst
else:
return [random.randint(min_val, max_val) for _ in range(n)]
# Sorting Algorithms
def bubble_sort(draw_info: DrawInformation, ascending: bool = True) -> Generator[bool, None, None]:
"""Enhanced Bubble Sort with visualization."""
lst = draw_info.lst
n = len(lst)
for i in range(n - 1):
swapped = False
for j in range(n - 1 - i):
draw_info.stats.comparisons += 1
draw_info.stats.array_accesses += 2
num1, num2 = lst[j], lst[j + 1]
# Visualize comparison
draw_array(draw_info, {j: draw_info.colors.comparing, j + 1: draw_info.colors.comparing}, True)
yield True
if (num1 > num2 and ascending) or (num1 < num2 and not ascending):
lst[j], lst[j + 1] = lst[j + 1], lst[j]
draw_info.stats.swaps += 1
swapped = True
# Visualize swap
draw_array(draw_info, {j: draw_info.colors.swapping, j + 1: draw_info.colors.swapping}, True)
yield True
# Mark sorted elements
for k in range(n - 1 - i, n):
draw_array(draw_info, {k: draw_info.colors.sorted}, True)
if not swapped:
break
# Mark all as sorted
sorted_colors = {i: draw_info.colors.sorted for i in range(n)}
draw_array(draw_info, sorted_colors, True)
return lst
def insertion_sort(draw_info: DrawInformation, ascending: bool = True) -> Generator[bool, None, None]:
"""Enhanced Insertion Sort with visualization."""
lst = draw_info.lst
for i in range(1, len(lst)):
current = lst[i]
j = i
# Highlight current element
draw_array(draw_info, {i: draw_info.colors.current}, True)
yield True
while j > 0:
draw_info.stats.comparisons += 1
draw_info.stats.array_accesses += 2
# Visualize comparison
draw_array(draw_info, {j-1: draw_info.colors.comparing, j: draw_info.colors.current}, True)
yield True
should_swap = (lst[j-1] > current and ascending) or (lst[j-1] < current and not ascending)
if not should_swap:
break
lst[j] = lst[j-1]
j -= 1
draw_info.stats.swaps += 1
# Visualize shift
draw_array(draw_info, {j: draw_info.colors.swapping, j+1: draw_info.colors.swapping}, True)
yield True
lst[j] = current
# Mark sorted portion
sorted_colors = {k: draw_info.colors.sorted for k in range(i + 1)}
draw_array(draw_info, sorted_colors, True)
yield True
return lst
def selection_sort(draw_info: DrawInformation, ascending: bool = True) -> Generator[bool, None, None]:
"""Selection Sort with visualization."""
lst = draw_info.lst
n = len(lst)
for i in range(n):
min_max_idx = i
# Highlight current position
draw_array(draw_info, {i: draw_info.colors.current}, True)
yield True
for j in range(i + 1, n):
draw_info.stats.comparisons += 1
draw_info.stats.array_accesses += 2
# Visualize comparison
colors = {i: draw_info.colors.current, j: draw_info.colors.comparing, min_max_idx: draw_info.colors.accent}
draw_array(draw_info, colors, True)
yield True
if (ascending and lst[j] < lst[min_max_idx]) or (not ascending and lst[j] > lst[min_max_idx]):
min_max_idx = j
if min_max_idx != i:
lst[i], lst[min_max_idx] = lst[min_max_idx], lst[i]
draw_info.stats.swaps += 1
# Visualize swap
draw_array(draw_info, {i: draw_info.colors.swapping, min_max_idx: draw_info.colors.swapping}, True)
yield True
# Mark as sorted
sorted_colors = {k: draw_info.colors.sorted for k in range(i + 1)}
draw_array(draw_info, sorted_colors, True)
yield True
return lst
def merge_sort(draw_info: DrawInformation, ascending: bool = True) -> Generator[bool, None, None]:
"""Merge Sort with visualization."""
def merge_sort_helper(lst: List[int], left: int, right: int) -> Generator[bool, None, None]:
if left < right:
mid = (left + right) // 2
# Highlight current range
colors = {i: draw_info.colors.current for i in range(left, right + 1)}
draw_array(draw_info, colors, True)
yield True
yield from merge_sort_helper(lst, left, mid)
yield from merge_sort_helper(lst, mid + 1, right)
yield from merge(lst, left, mid, right, ascending)
def merge(lst: List[int], left: int, mid: int, right: int, ascending: bool) -> Generator[bool, None, None]:
left_arr = lst[left:mid + 1]
right_arr = lst[mid + 1:right + 1]
i = j = 0
k = left
while i < len(left_arr) and j < len(right_arr):
draw_info.stats.comparisons += 1
draw_info.stats.array_accesses += 2
# Visualize merge process
colors = {
left + i: draw_info.colors.comparing,
mid + 1 + j: draw_info.colors.comparing,
k: draw_info.colors.current
}
draw_array(draw_info, colors, True)
yield True
if (ascending and left_arr[i] <= right_arr[j]) or (not ascending and left_arr[i] >= right_arr[j]):
lst[k] = left_arr[i]
i += 1
else:
lst[k] = right_arr[j]
j += 1
k += 1
# Show merged element
draw_array(draw_info, {k-1: draw_info.colors.sorted}, True)
yield True
# Copy remaining elements
while i < len(left_arr):
lst[k] = left_arr[i]
draw_array(draw_info, {k: draw_info.colors.sorted}, True)
yield True
i += 1
k += 1
while j < len(right_arr):
lst[k] = right_arr[j]
draw_array(draw_info, {k: draw_info.colors.sorted}, True)
yield True
j += 1
k += 1
yield from merge_sort_helper(draw_info.lst, 0, len(draw_info.lst) - 1)
return draw_info.lst
def quick_sort(draw_info: DrawInformation, ascending: bool = True) -> Generator[bool, None, None]:
"""Quick Sort with visualization."""
def quick_sort_helper(lst: List[int], low: int, high: int) -> Generator[bool, None, None]:
if low < high:
# Highlight current range
colors = {i: draw_info.colors.current for i in range(low, high + 1)}
draw_array(draw_info, colors, True)
yield True
pi = yield from partition(lst, low, high, ascending)
yield from quick_sort_helper(lst, low, pi - 1)
yield from quick_sort_helper(lst, pi + 1, high)
def partition(lst: List[int], low: int, high: int, ascending: bool) -> Generator[int, None, None]:
pivot = lst[high]
i = low - 1
# Highlight pivot
draw_array(draw_info, {high: draw_info.colors.accent}, True)
yield True
for j in range(low, high):
draw_info.stats.comparisons += 1
draw_info.stats.array_accesses += 2
# Visualize comparison with pivot
colors = {j: draw_info.colors.comparing, high: draw_info.colors.accent}
if i >= 0:
colors[i] = draw_info.colors.current
draw_array(draw_info, colors, True)
yield True
if (ascending and lst[j] <= pivot) or (not ascending and lst[j] >= pivot):
i += 1
if i != j:
lst[i], lst[j] = lst[j], lst[i]
draw_info.stats.swaps += 1
# Visualize swap
draw_array(draw_info, {i: draw_info.colors.swapping, j: draw_info.colors.swapping}, True)
yield True
lst[i + 1], lst[high] = lst[high], lst[i + 1]
draw_info.stats.swaps += 1
# Visualize final pivot placement
draw_array(draw_info, {i + 1: draw_info.colors.sorted}, True)
yield True
return i + 1
yield from quick_sort_helper(draw_info.lst, 0, len(draw_info.lst) - 1)
return draw_info.lst
def heap_sort(draw_info: DrawInformation, ascending: bool = True) -> Generator[bool, None, None]:
"""Heap Sort with visualization."""
def heapify(lst: List[int], n: int, i: int, ascending: bool) -> Generator[bool, None, None]:
largest_smallest = i
left = 2 * i + 1
right = 2 * i + 2
# Highlight current node
draw_array(draw_info, {i: draw_info.colors.current}, True)
yield True
if left < n:
draw_info.stats.comparisons += 1
draw_info.stats.array_accesses += 2
# Visualize comparison
draw_array(draw_info, {i: draw_info.colors.current, left: draw_info.colors.comparing}, True)
yield True
if (ascending and lst[left] > lst[largest_smallest]) or (not ascending and lst[left] < lst[largest_smallest]):
largest_smallest = left
if right < n:
draw_info.stats.comparisons += 1
draw_info.stats.array_accesses += 2
# Visualize comparison
colors = {i: draw_info.colors.current, right: draw_info.colors.comparing}
if largest_smallest != i:
colors[largest_smallest] = draw_info.colors.accent
draw_array(draw_info, colors, True)
yield True
if (ascending and lst[right] > lst[largest_smallest]) or (not ascending and lst[right] < lst[largest_smallest]):
largest_smallest = right
if largest_smallest != i:
lst[i], lst[largest_smallest] = lst[largest_smallest], lst[i]
draw_info.stats.swaps += 1
# Visualize swap
draw_array(draw_info, {i: draw_info.colors.swapping, largest_smallest: draw_info.colors.swapping}, True)
yield True
yield from heapify(lst, n, largest_smallest, ascending)
lst = draw_info.lst
n = len(lst)
# Build heap
for i in range(n // 2 - 1, -1, -1):
yield from heapify(lst, n, i, ascending)
# Extract elements from heap
for i in range(n - 1, 0, -1):
lst[0], lst[i] = lst[i], lst[0]
draw_info.stats.swaps += 1
# Visualize swap
draw_array(draw_info, {0: draw_info.colors.swapping, i: draw_info.colors.sorted}, True)
yield True
yield from heapify(lst, i, 0, ascending)
# Mark all as sorted
sorted_colors = {i: draw_info.colors.sorted for i in range(n)}
draw_array(draw_info, sorted_colors, True)
return lst
def main():
"""Enhanced main function with modern features."""
pygame.init()
# Configuration
WINDOW_WIDTH = 1200
WINDOW_HEIGHT = 800
FPS = 60
# Algorithm settings
n = 60
min_val = 10
max_val = 200
# Initialize
lst = generate_list(n, min_val, max_val)
draw_info = DrawInformation(WINDOW_WIDTH, WINDOW_HEIGHT, lst)
# State variables
run = True
clock = pygame.time.Clock()
sorting = False
ascending = True
speed = 5
step_mode = False
# Algorithm selection
algorithms = {
1: (bubble_sort, "Bubble Sort"),
2: (insertion_sort, "Insertion Sort"),
3: (selection_sort, "Selection Sort"),
4: (merge_sort, "Merge Sort"),
5: (quick_sort, "Quick Sort"),
6: (heap_sort, "Heap Sort")
}
current_algorithm = 1
sorting_algorithm, algo_name = algorithms[current_algorithm]
sorting_generator = None
while run:
# Adjust frame rate based on speed
clock.tick(FPS if not sorting else max(1, speed * 6))
# Handle sorting
if sorting and sorting_generator:
try:
for _ in range(1 if step_mode else max(1, speed // 2)):
next(sorting_generator)
if step_mode:
break
except StopIteration:
sorting = False
draw_info.state = SortingState.COMPLETED
draw_info.stats.end_sorting()
sorting_generator = None
# Draw interface
if not sorting or step_mode:
draw_complete(draw_info, algo_name, ascending, speed)
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
key = event.key
# Basic controls
if key == pygame.K_ESCAPE:
run = False
elif key == pygame.K_r:
lst = generate_list(n, min_val, max_val)
draw_info.set_list(lst)
draw_info.state = SortingState.IDLE
sorting = False
sorting_generator = None
elif key == pygame.K_SPACE and not sorting:
sorting = True
draw_info.state = SortingState.SORTING
draw_info.stats.start_sorting()
sorting_generator = sorting_algorithm(draw_info, ascending)
elif key == pygame.K_a and not sorting:
ascending = True
elif key == pygame.K_d and not sorting:
ascending = False
elif key == pygame.K_t:
draw_info.cycle_theme()
elif key == pygame.K_s:
step_mode = not step_mode
# Speed control
elif key == pygame.K_UP and speed < 10:
speed += 1
elif key == pygame.K_DOWN and speed > 1:
speed -= 1
# Algorithm selection
elif key in [pygame.K_1, pygame.K_2, pygame.K_3, pygame.K_4, pygame.K_5, pygame.K_6]:
if not sorting:
current_algorithm = key - pygame.K_0
if current_algorithm in algorithms:
sorting_algorithm, algo_name = algorithms[current_algorithm]
draw_info.state = SortingState.IDLE
# Array size control
elif key == pygame.K_MINUS and n > 10 and not sorting:
n = max(10, n - 10)
lst = generate_list(n, min_val, max_val)
draw_info.set_list(lst)
elif key == pygame.K_EQUALS and n < 200 and not sorting:
n = min(200, n + 10)
lst = generate_list(n, min_val, max_val)
draw_info.set_list(lst)
# Distribution types
elif key == pygame.K_F1 and not sorting:
lst = generate_list(n, min_val, max_val, "random")
draw_info.set_list(lst)
elif key == pygame.K_F2 and not sorting:
lst = generate_list(n, min_val, max_val, "sorted")
draw_info.set_list(lst)
elif key == pygame.K_F3 and not sorting:
lst = generate_list(n, min_val, max_val, "reverse")
draw_info.set_list(lst)
elif key == pygame.K_F4 and not sorting:
lst = generate_list(n, min_val, max_val, "nearly_sorted")
draw_info.set_list(lst)
pygame.quit()
if __name__ == "__main__":
main()