Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
541 lines (448 loc) · 22.6 KB
/
Copy pathmain.py
File metadata and controls
541 lines (448 loc) · 22.6 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
"""
Interactive Algorithm Visualizer
Main application file for visualizing Binary Search, Quicksort, and Mergesort
"""
# Core GUI imports
import tkinter as tk
from tkinter import ttk, messagebox
# External libraries
import sv_ttk
# Standard library
import random
import time
# Local modules
from algorithms import quicksort_generator, mergesort_generator, binary_search_generator
from visualizer import ArrayVisualizer
class AlgorithmVisualizerApp:
def __init__(self, root):
self.root = root
self.root.title("Interactive Algorithm Visualizer")
self.root.geometry("1200x750")
self.root.resizable(True, True)
self.root.minsize(1000, 600) # Set minimum window size
# Apply modern theme
self.current_theme = "dark"
sv_ttk.set_theme(self.current_theme)
# Consistent padding values
self.PADDING = {
'small': 5,
'medium': 10,
'large': 15,
'xlarge': 20
}
# Application state
self.array = []
self.array_size = 20
self.min_value = 1
self.max_value = 100
self.animation_speed = 500 # milliseconds
self.is_playing = False
self.is_sorted = False
self.current_algorithm = None
self.algorithm_generator = None
# Color scheme optimized for dark theme
self.colors = {
'default': '#4A9EFF', # Bright blue
'comparing': '#FF6B6B', # Bright red
'pivot': '#FFD93D', # Bright yellow
'sorted': '#6BCF7F', # Bright green
'found': '#4ECDC4', # Bright cyan
'searching': '#A8E6CF', # Light green
'merging': '#FF8B94', # Light red
'partitioning': '#B4A7D6' # Light purple
}
self.setup_ui()
self.generate_array()
def setup_ui(self):
"""Create the main UI layout"""
# Configure root grid
self.root.columnconfigure(0, weight=1)
self.root.rowconfigure(0, weight=1)
# Main container with consistent padding
main_frame = ttk.Frame(self.root, padding=self.PADDING['large'])
main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
main_frame.columnconfigure(0, weight=1)
main_frame.rowconfigure(1, weight=1)
# Control Panel (Top)
self.create_control_panel(main_frame)
# Visualization Canvas (Center)
self.create_visualization_canvas(main_frame)
# Status Bar (Bottom)
self.create_status_bar(main_frame)
def create_control_panel(self, parent):
control_frame = ttk.LabelFrame(parent, text="Controls", padding=self.PADDING['medium'])
control_frame.grid(row=0, column=0, sticky=(tk.W, tk.E), pady=(0, self.PADDING['medium']))
control_frame.columnconfigure(0, weight=1)
# Row 1: Array controls
row1_frame = ttk.Frame(control_frame)
row1_frame.grid(row=0, column=0, sticky=(tk.W, tk.E), pady=(0, self.PADDING['medium']))
# Array size
ttk.Label(row1_frame, text="Array Size:").pack(side=tk.LEFT, padx=(0, self.PADDING['small']))
self.size_var = tk.IntVar(value=self.array_size)
# Bind to variable changes to catch both spinbox clicks and direct typing
self.size_var.trace('w', lambda *args: self.update_array_size())
size_spin = ttk.Spinbox(row1_frame, from_=5, to=50, width=10,
textvariable=self.size_var, command=self.update_array_size)
size_spin.pack(side=tk.LEFT, padx=(0, self.PADDING['xlarge']))
self.generate_btn = ttk.Button(row1_frame, text="Generate Array",
command=self.generate_array)
self.generate_btn.pack(side=tk.LEFT, padx=(0, self.PADDING['medium']))
# Custom array input
ttk.Label(row1_frame, text="Custom Array (comma-separated):").pack(side=tk.LEFT, padx=(0, self.PADDING['small']))
self.custom_array_var = tk.StringVar()
custom_entry = ttk.Entry(row1_frame, width=30, textvariable=self.custom_array_var)
custom_entry.pack(side=tk.LEFT, padx=(0, self.PADDING['small']))
self.load_custom_btn = ttk.Button(row1_frame, text="Load Custom",
command=self.load_custom_array)
self.load_custom_btn.pack(side=tk.LEFT)
# Row 2: Algorithm controls
row2_frame = ttk.Frame(control_frame)
row2_frame.grid(row=1, column=0, sticky=(tk.W, tk.E), pady=(0, self.PADDING['medium']))
# Sorting algorithm selector
ttk.Label(row2_frame, text="Sorting Algorithm:").pack(side=tk.LEFT, padx=(0, self.PADDING['small']))
self.sort_algo_var = tk.StringVar(value="Quicksort")
algo_combo = ttk.Combobox(row2_frame, textvariable=self.sort_algo_var,
values=["Quicksort", "Mergesort"], width=15, state="readonly")
algo_combo.pack(side=tk.LEFT, padx=(0, self.PADDING['medium']))
# Sort button
self.sort_btn = ttk.Button(row2_frame, text="Start Sorting",
command=self.start_sorting)
self.sort_btn.pack(side=tk.LEFT, padx=(0, self.PADDING['xlarge']))
# Binary search controls
ttk.Label(row2_frame, text="Search Target:").pack(side=tk.LEFT, padx=(0, self.PADDING['small']))
self.search_target_var = tk.IntVar()
search_entry = ttk.Entry(row2_frame, width=10, textvariable=self.search_target_var)
search_entry.pack(side=tk.LEFT, padx=(0, self.PADDING['small']))
self.search_btn = ttk.Button(row2_frame, text="Start Binary Search",
command=self.start_binary_search)
self.search_btn.pack(side=tk.LEFT)
# Row 3: Animation controls
row3_frame = ttk.Frame(control_frame)
row3_frame.grid(row=2, column=0, sticky=(tk.W, tk.E))
# Speed control
ttk.Label(row3_frame, text="Animation Speed:").pack(side=tk.LEFT, padx=(0, self.PADDING['small']))
self.speed_var = tk.IntVar(value=self.animation_speed)
speed_scale = ttk.Scale(row3_frame, from_=10, to=2000, orient=tk.HORIZONTAL,
variable=self.speed_var, command=self.update_speed, length=200)
speed_scale.pack(side=tk.LEFT, padx=(0, self.PADDING['small']))
self.speed_label = ttk.Label(row3_frame, text=f"{self.animation_speed}ms")
self.speed_label.pack(side=tk.LEFT, padx=(0, self.PADDING['xlarge']))
# Play/Pause/Reset buttons
self.play_pause_btn = ttk.Button(row3_frame, text="Play",
command=self.toggle_play_pause, state="disabled")
self.play_pause_btn.pack(side=tk.LEFT, padx=(0, self.PADDING['small']))
self.step_btn = ttk.Button(row3_frame, text="Next Step",
command=self.step_animation, state="disabled")
self.step_btn.pack(side=tk.LEFT, padx=(0, self.PADDING['small']))
self.reset_btn = ttk.Button(row3_frame, text="Reset",
command=self.reset_animation, state="disabled")
self.reset_btn.pack(side=tk.LEFT, padx=(0, self.PADDING['xlarge']))
# Algorithm complexity info
self.complexity_label = ttk.Label(row3_frame, text="", font=("Segoe UI", 10, "italic"))
self.complexity_label.pack(side=tk.LEFT)
# Theme toggle button (far right)
self.theme_btn = ttk.Button(row3_frame, text="🌙 Light Theme",
command=self.toggle_theme, width=12)
self.theme_btn.pack(side=tk.RIGHT)
def create_visualization_canvas(self, parent):
"""Create the visualization canvas"""
canvas_frame = ttk.LabelFrame(parent, text="Visualization", padding=self.PADDING['medium'])
canvas_frame.grid(row=1, column=0, sticky=(tk.W, tk.E, tk.N, tk.S), pady=(0, self.PADDING['medium']))
canvas_frame.columnconfigure(0, weight=1)
canvas_frame.rowconfigure(0, weight=1)
# Create the visualizer with dynamic width
self.visualizer = ArrayVisualizer(canvas_frame, width=1150, height=420,
colors=self.colors)
self.visualizer.canvas.pack(pady=(0, self.PADDING['medium']))
# Legend
self.create_legend(canvas_frame)
def create_legend(self, parent):
"""Create color legend"""
legend_frame = ttk.Frame(parent)
legend_frame.pack(pady=(self.PADDING['medium'], 0))
# Legend title
ttk.Label(legend_frame, text="Color Legend:", font=("Segoe UI", 10, "bold")).pack(side=tk.LEFT, padx=(0, self.PADDING['medium']))
legend_items = [
("Default", self.colors['default']),
("Comparing", self.colors['comparing']),
("Pivot", self.colors['pivot']),
("Sorted", self.colors['sorted']),
("Searching", self.colors['searching']),
("Found", self.colors['found'])
]
for label, color in legend_items:
item_frame = ttk.Frame(legend_frame)
item_frame.pack(side=tk.LEFT, padx=self.PADDING['small'])
color_box = tk.Canvas(item_frame, width=20, height=20, highlightthickness=0)
color_box.create_rectangle(0, 0, 20, 20, fill=color, outline="#666666", width=1)
color_box.pack(side=tk.LEFT, padx=(0, self.PADDING['small']//2))
ttk.Label(item_frame, text=label, font=("Segoe UI", 9)).pack(side=tk.LEFT)
def create_status_bar(self, parent):
"""Create the status bar"""
status_frame = ttk.Frame(parent)
status_frame.grid(row=2, column=0, sticky=(tk.W, tk.E), pady=(self.PADDING['medium'], 0))
status_frame.columnconfigure(0, weight=1)
# Create a styled status bar frame
status_inner = ttk.Frame(status_frame, style="Card.TFrame")
status_inner.pack(fill=tk.X, padx=self.PADDING['small'], pady=self.PADDING['small'])
self.status_label = ttk.Label(status_inner, text="Ready", font=("Segoe UI", 10))
self.status_label.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=self.PADDING['small'])
self.step_counter_label = ttk.Label(status_inner, text="Steps: 0", font=("Segoe UI", 10, "bold"))
self.step_counter_label.pack(side=tk.RIGHT, padx=self.PADDING['small'])
def update_array_size(self):
"""Update array size from spinbox"""
try:
old_size = self.array_size
new_size = self.size_var.get()
if new_size > 0: # Only update if valid
self.array_size = new_size
except tk.TclError:
# Handle empty or invalid input gracefully
pass
def update_speed(self, value):
"""Update animation speed"""
self.animation_speed = int(float(value))
self.speed_label.config(text=f"{self.animation_speed}ms")
def generate_array(self):
"""Generate a random array"""
self.array = [random.randint(self.min_value, self.max_value)
for _ in range(self.array_size)]
self.is_sorted = False
# Resize canvas for better visualization
self.visualizer.resize_canvas_for_array(self.array_size)
self.visualizer.display_array(self.array)
self.update_status(f"Generated random array with {len(self.array)} elements")
self.reset_animation()
def load_custom_array(self):
"""Load a custom array from input"""
try:
input_str = self.custom_array_var.get().strip()
if not input_str:
raise ValueError("Empty input")
self.array = [int(x.strip()) for x in input_str.split(',')]
self.array_size = len(self.array)
self.size_var.set(self.array_size)
self.is_sorted = all(self.array[i] <= self.array[i+1]
for i in range(len(self.array)-1))
# Resize canvas for better visualization
self.visualizer.resize_canvas_for_array(self.array_size)
self.visualizer.display_array(self.array)
self.update_status(f"Loaded custom array with {len(self.array)} elements (sorted: {self.is_sorted})")
self.reset_animation()
except Exception as e:
messagebox.showerror("Error", f"Invalid array format: {e}")
def start_sorting(self):
"""Start the sorting animation"""
if not self.array:
messagebox.showwarning("Warning", "Please generate an array first")
return
self.reset_animation()
algo_name = self.sort_algo_var.get()
if algo_name == "Quicksort":
self.algorithm_generator = quicksort_generator(self.array.copy())
self.complexity_label.config(text="Time: O(n log n) avg, O(n²) worst | Space: O(log n)")
else: # Mergesort
self.algorithm_generator = mergesort_generator(self.array.copy())
self.complexity_label.config(text="Time: O(n log n) | Space: O(n)")
self.current_algorithm = "sorting"
self.enable_animation_controls()
self.update_status(f"Starting {algo_name}")
self.is_playing = True
self.play_pause_btn.config(text="Pause")
self.animate()
def start_binary_search(self):
"""Start binary search animation"""
if not self.array:
messagebox.showwarning("Warning", "Please generate an array first")
return
target = self.search_target_var.get()
if not target:
messagebox.showwarning("Warning", "Please enter a search target")
return
# Ensure array is sorted
if not self.is_sorted:
response = messagebox.askyesno("Array Not Sorted",
"Array must be sorted for binary search. Sort it now?")
if response:
self.array.sort()
self.is_sorted = True
self.visualizer.display_array(self.array)
self.update_status("Array sorted")
else:
return
self.reset_animation()
self.algorithm_generator = binary_search_generator(self.array.copy(), target)
self.current_algorithm = "binary_search"
self.complexity_label.config(text="Time: O(log n) | Space: O(1)")
self.enable_animation_controls()
self.update_status(f"Searching for {target}")
self.is_playing = True
self.play_pause_btn.config(text="Pause")
self.animate()
def animate(self):
"""Main animation loop"""
if not self.is_playing or not self.algorithm_generator:
return
try:
state = next(self.algorithm_generator)
self.process_state(state)
self.root.after(self.animation_speed, self.animate)
except StopIteration:
self.animation_complete()
def process_state(self, state):
"""Process and display algorithm state"""
if self.current_algorithm == "sorting":
# Update the main array with the current state
self.array = state['array']
self.visualizer.display_array(state['array'], state.get('highlights', {}))
self.update_status(state.get('description', ''))
self.step_counter_label.config(text=f"Steps: {state.get('step', 0)}")
if state.get('sorted', False):
self.is_sorted = True
elif self.current_algorithm == "binary_search":
highlights = {}
if 'low' in state and 'high' in state:
for i in range(state['low'], state['high'] + 1):
highlights[i] = 'searching'
if 'mid' in state:
highlights[state['mid']] = 'comparing'
if 'found_index' in state:
highlights[state['found_index']] = 'found'
self.visualizer.display_array(self.array, highlights)
self.update_status(state.get('description', ''))
self.step_counter_label.config(text=f"Steps: {state.get('step', 0)}")
def step_animation(self):
"""Execute one step of the animation"""
if not self.algorithm_generator:
return
try:
state = next(self.algorithm_generator)
self.process_state(state)
except StopIteration:
self.animation_complete()
def toggle_play_pause(self):
"""Toggle between play and pause"""
self.is_playing = not self.is_playing
self.play_pause_btn.config(text="Pause" if self.is_playing else "Play")
if self.is_playing:
self.animate()
def reset_animation(self):
"""Reset the current animation"""
self.is_playing = False
self.algorithm_generator = None
self.current_algorithm = None
self.disable_animation_controls()
self.visualizer.display_array(self.array)
# Update status based on current array state
if self.is_sorted:
self.update_status("Array is sorted. Ready for binary search or re-sorting.")
else:
self.update_status("Ready")
self.step_counter_label.config(text="Steps: 0")
self.complexity_label.config(text="")
def animation_complete(self):
"""Handle animation completion"""
self.is_playing = False
self.play_pause_btn.config(text="Play", state="disabled")
self.step_btn.config(state="disabled")
if self.current_algorithm == "sorting":
self.is_sorted = True
self.update_status("Sorting complete! You can now use binary search.")
# Enable controls for further operations
self.enable_post_sorting_controls()
elif self.current_algorithm == "binary_search":
# Status already updated by the algorithm
# Enable controls for further operations
self.enable_post_search_controls()
def enable_animation_controls(self):
"""Enable animation control buttons"""
self.play_pause_btn.config(state="normal")
self.step_btn.config(state="normal")
self.reset_btn.config(state="normal")
self.generate_btn.config(state="disabled")
self.load_custom_btn.config(state="disabled")
self.sort_btn.config(state="disabled")
self.search_btn.config(state="disabled")
def disable_animation_controls(self):
"""Disable animation control buttons"""
self.play_pause_btn.config(text="Play", state="disabled")
self.step_btn.config(state="disabled")
self.reset_btn.config(state="disabled")
self.generate_btn.config(state="normal")
self.load_custom_btn.config(state="normal")
self.sort_btn.config(state="normal")
self.search_btn.config(state="normal")
def enable_post_sorting_controls(self):
"""Enable appropriate controls after sorting is complete"""
# Animation controls
self.play_pause_btn.config(text="Play", state="disabled")
self.step_btn.config(state="disabled")
self.reset_btn.config(state="normal") # Keep reset enabled
# Array generation controls
self.generate_btn.config(state="normal")
self.load_custom_btn.config(state="normal")
# Algorithm controls - enable binary search since array is now sorted
self.sort_btn.config(state="normal") # Allow re-sorting
self.search_btn.config(state="normal") # Enable binary search
def enable_post_search_controls(self):
"""Enable appropriate controls after binary search is complete"""
# Animation controls
self.play_pause_btn.config(text="Play", state="disabled")
self.step_btn.config(state="disabled")
self.reset_btn.config(state="normal")
# Array generation controls
self.generate_btn.config(state="normal")
self.load_custom_btn.config(state="normal")
# Algorithm controls - enable all since search is complete
self.sort_btn.config(state="normal")
self.search_btn.config(state="normal") # Allow another search
def update_status(self, message):
"""Update the status bar"""
self.status_label.config(text=message)
def toggle_theme(self):
"""Toggle between light and dark theme"""
if self.current_theme == "dark":
self.current_theme = "light"
self.theme_btn.config(text="🌙 Dark Theme")
# Update canvas background for light theme
self.visualizer.canvas.config(bg='#ffffff', highlightbackground='#cccccc')
# Update colors for light theme
self.colors.update({
'default': '#2980b9', # Darker blue
'comparing': '#c0392b', # Darker red
'pivot': '#d68910', # Darker yellow
'sorted': '#27ae60', # Keep green
'found': '#16a085', # Darker cyan
'searching': '#8e44ad', # Darker purple
'merging': '#e67e22', # Darker orange
'partitioning': '#9b59b6' # Darker purple
})
else:
self.current_theme = "dark"
self.theme_btn.config(text="🌙 Light Theme")
# Update canvas background for dark theme
self.visualizer.canvas.config(bg='#1e1e1e', highlightbackground='#404040')
# Restore dark theme colors
self.colors.update({
'default': '#4A9EFF', # Bright blue
'comparing': '#FF6B6B', # Bright red
'pivot': '#FFD93D', # Bright yellow
'sorted': '#6BCF7F', # Bright green
'found': '#4ECDC4', # Bright cyan
'searching': '#A8E6CF', # Light green
'merging': '#FF8B94', # Light red
'partitioning': '#B4A7D6' # Light purple
})
# Apply the new theme
sv_ttk.set_theme(self.current_theme)
# Update visualizer colors
self.visualizer.colors = self.colors
# Refresh the current display
if self.array:
self.visualizer.display_array(self.array)
def main():
root = tk.Tk()
app = AlgorithmVisualizerApp(root)
root.mainloop()
if __name__ == "__main__":
main()