-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisualizer.js
More file actions
5933 lines (5147 loc) · 233 KB
/
Copy pathvisualizer.js
File metadata and controls
5933 lines (5147 loc) · 233 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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Use TimeFormatter class if available, otherwise use fallback functions
// This maintains backward compatibility while using OOP structure
let globalStopFlag = false;
// Fallback functions for backward compatibility
function getBestTimeFormat(ms) {
if (typeof TimeFormatter !== 'undefined') {
return TimeFormatter.getBestFormat(ms);
}
// Fallback implementation
if (ms >= 86400000) return 'd';
if (ms >= 3600000) return 'h';
if (ms >= 60000) return 'm';
if (ms >= 2000) return 's';
return 'ms';
}
function formatTimeValue(ms, format = 'ms') {
if (typeof TimeFormatter !== 'undefined') {
if (format === 'auto' || (!format || format === 'ms')) {
if (ms >= 2000) {
format = TimeFormatter.getBestFormat(ms);
}
}
return TimeFormatter.format(ms, format);
}
// Fallback implementation (original code)
if (format === 'auto' || (!format || format === 'ms')) {
if (ms >= 2000) {
format = getBestTimeFormat(ms);
}
}
if (ms >= 86400000 && format !== 'd') {
format = 'd';
} else if (ms >= 3600000 && ms < 86400000 && format !== 'd' && format !== 'h') {
format = 'h';
} else if (ms >= 60000 && ms < 3600000 && format !== 'd' && format !== 'h' && format !== 'm') {
format = 'm';
} else if (ms >= 2000 && ms < 60000 && format !== 'd' && format !== 'h' && format !== 'm' && format !== 's') {
format = 's';
}
switch (format) {
case 's':
return `${(ms / 1000).toFixed(3)}s`;
case 'm':
const minutes = Math.floor(ms / 60000);
const seconds = ((ms % 60000) / 1000).toFixed(1);
return minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`;
case 'h':
const hours = Math.floor(ms / 3600000);
const remainingMs = ms % 3600000;
const mins = Math.floor(remainingMs / 60000);
const secs = ((remainingMs % 60000) / 1000).toFixed(1);
if (hours > 0) {
return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;
}
return mins > 0 ? `${mins}m ${secs}s` : `${secs}s`;
case 'd':
const days = Math.floor(ms / 86400000);
const remainingMsAfterDays = ms % 86400000;
const hrs = Math.floor(remainingMsAfterDays / 3600000);
const remainingMsAfterHours = remainingMsAfterDays % 3600000;
const minsAfterHours = Math.floor(remainingMsAfterHours / 60000);
if (days > 0) {
return hrs > 0 ? `${days}d ${hrs}h` : `${days}d`;
}
return hrs > 0 ? `${hrs}h ${minsAfterHours}m` : `${minsAfterHours}m`;
case 'ms':
default:
return `${Math.round(ms)}ms`;
}
}
let rawTimeValues = {
sortTime: 0,
pathTime: 0,
searchTime: 0,
graphTime: 0,
dpTime: 0,
stringTime: 0,
mathTime: 0
};
// Use VisualizationManager if available, otherwise use fallback
function stopAllVisualizations() {
globalStopFlag = true;
// Use VisualizationManager if available
if (typeof VisualizationManager !== 'undefined' && window.visualizationManager) {
window.visualizationManager.stopAll();
} else {
// Fallback to direct references
if (sortingVisualizer) sortingVisualizer.stop();
if (searchingVisualizer) searchingVisualizer.stop();
if (pathfindingVisualizer) pathfindingVisualizer.stop();
if (treeVisualizer) treeVisualizer.stop();
if (graphVisualizer) graphVisualizer.stop();
if (dpVisualizer) dpVisualizer.stop();
if (stringVisualizer) stringVisualizer.stop();
if (languageArena) languageArena.stop();
}
// Reset flag after a short delay
setTimeout(() => { globalStopFlag = false; }, 100);
}
// Make it globally available
if (typeof window !== 'undefined') {
window.stopAllVisualizations = stopAllVisualizations;
}
// Use LanguageManager if available, otherwise use fallback
// This maintains backward compatibility while using OOP structure
// Initialize language manager instance
let languageManager = null;
if (typeof LanguageManager !== 'undefined') {
languageManager = new LanguageManager();
if (typeof window !== 'undefined') {
window.languageManager = languageManager;
}
}
// Fallback LANGUAGE_SPEED for backward compatibility
const LANGUAGE_SPEED = {
cpp: 1.0, // Baseline (fastest) - Native compiled
rust: 1.0, // Similar to C++ - Native compiled, zero-cost abstractions
c: 1.0, // Similar to C++ - Native compiled
go: 1.15, // Slightly slower - Compiled, GC overhead
swift: 1.2, // Fast - Native compiled, ARC
java: 1.4, // JIT compiled - HotSpot optimization
csharp: 1.5, // Similar to Java - .NET JIT
kotlin: 1.6, // JVM-based - Similar to Java
node: 1.8, // V8 JIT - Highly optimized JavaScript
deno: 1.9, // V8 based - Similar to Node, slight overhead
javascript: 2.0, // V8 optimized - Modern JS engines are fast
typescript: 2.0, // Compiles to JS - Same performance as JS
elixir: 4.5, // BEAM VM - Good for concurrency, slower for CPU-bound
python: 7.5, // Interpreted - CPython is slower, PyPy faster
php: 9.0, // Interpreted - Server-side optimized
bash: 10.0, // Shell script - Interpreted, slower than Python
ruby: 11.0 // Interpreted - Slower than Python
};
// Fallback functions for backward compatibility
let _cachedLanguageIcons = null;
let _cachedTheme = null;
function getLanguageIcons() {
// Use LanguageManager if available
if (languageManager) {
return languageManager.getIcons();
}
// Fallback implementation
const currentTheme = document.documentElement.getAttribute('data-theme');
if (_cachedLanguageIcons && _cachedTheme === currentTheme) {
return _cachedLanguageIcons;
}
const isDarkMode = currentTheme !== 'light';
_cachedLanguageIcons = {
java: 'icons/java.svg',
python: 'icons/python.svg',
deno: isDarkMode ? 'icons/deno-light.svg' : 'icons/deno.png',
node: 'icons/nodejs.svg',
typescript: 'icons/typescript.svg',
php: 'icons/php.svg',
elixir: 'icons/elixir.svg',
kotlin: 'icons/kotlin.svg',
swift: 'icons/swift.svg',
ruby: 'icons/ruby.svg',
javascript: 'icons/javascript.svg',
cpp: 'icons/cplusplus.svg',
csharp: 'icons/csharp.svg',
rust: isDarkMode ? 'icons/rust-dark.png' : 'icons/rust.svg',
go: 'icons/go.svg',
c: 'icons/cplusplus.svg',
bash: 'icons/bash.svg'
};
_cachedTheme = currentTheme;
return _cachedLanguageIcons;
}
// Cache language info
let _cachedLanguageInfo = null;
function getLanguageInfo() {
// Use LanguageManager if available
if (languageManager) {
return languageManager.getInfo();
}
// Fallback implementation
const icons = getLanguageIcons();
if (!_cachedLanguageInfo || _cachedLanguageInfo.rust.icon !== icons.rust) {
_cachedLanguageInfo = {
javascript: { name: 'JavaScript', symbol: 'JS', color: '#f7df1e', icon: icons.javascript },
python: { name: 'Python', symbol: 'PY', color: '#3776ab', icon: icons.python },
java: { name: 'Java', symbol: 'JV', color: '#007396', icon: icons.java },
cpp: { name: 'C++', symbol: 'C++', color: '#00599c', icon: icons.cpp },
csharp: { name: 'C#', symbol: 'C#', color: '#239120', icon: icons.csharp },
go: { name: 'Go', symbol: 'GO', color: '#00add8', icon: icons.go },
rust: { name: 'Rust', symbol: 'RS', color: '#dea584', icon: icons.rust },
ruby: { name: 'Ruby', symbol: 'RB', color: '#cc342d', icon: icons.ruby },
php: { name: 'PHP', symbol: 'PHP', color: '#777bb4', icon: icons.php },
elixir: { name: 'Elixir', symbol: 'EX', color: '#6e4a7e', icon: icons.elixir },
node: { name: 'Node.js', symbol: 'ND', color: '#339933', icon: icons.node },
deno: { name: 'Deno', symbol: 'DN', color: '#000000', icon: icons.deno },
kotlin: { name: 'Kotlin', symbol: 'KT', color: '#7F52FF', icon: icons.kotlin },
swift: { name: 'Swift', symbol: 'SW', color: '#FA7343', icon: icons.swift },
typescript: { name: 'TypeScript', symbol: 'TS', color: '#3178c6', icon: icons.typescript },
c: { name: 'C', symbol: 'C', color: '#a8b9cc', icon: icons.c },
bash: { name: 'Bash', symbol: 'SH', color: '#4EAA25', icon: icons.bash }
};
}
return _cachedLanguageInfo;
}
// Initialize cached values (for backward compatibility)
const LANGUAGE_ICONS = getLanguageIcons();
const LANGUAGE_INFO = getLanguageInfo();
function updateRustIcons() {
_cachedLanguageInfo = null;
const icons = getLanguageIcons();
const rustIcon = icons.rust;
requestAnimationFrame(() => {
const rustImages = document.querySelectorAll('img[src*="rust"]');
rustImages.forEach(img => {
if (img.src.includes('rust')) {
img.src = rustIcon;
}
});
});
// Update cached LANGUAGE_INFO
if (_cachedLanguageInfo && _cachedLanguageInfo.rust) {
_cachedLanguageInfo.rust.icon = rustIcon;
}
}
function updateDenoIcons() {
_cachedLanguageInfo = null;
const icons = getLanguageIcons();
const denoIcon = icons.deno;
requestAnimationFrame(() => {
const denoImages = document.querySelectorAll('img[src*="deno"]');
denoImages.forEach(img => {
if (img.src.includes('deno')) {
img.src = denoIcon;
}
});
});
if (_cachedLanguageInfo && _cachedLanguageInfo.deno) {
_cachedLanguageInfo.deno.icon = denoIcon;
}
}
class SortingVisualizer {
constructor() {
this.array = [];
this.size = 30;
this.speed = 50;
this.isRunning = false;
this.isPaused = false;
this.shouldStop = false;
this.comparisons = 0;
this.swaps = 0;
this.currentAlgorithm = 'bubbleSort';
this.container = document.getElementById('sortingBars');
this.startTime = null;
this.pausedTime = 0; // Accumulated paused time
this.isCompareMode = false;
this.compareResults = { algo1: null, algo2: null };
this.isCompareRunning = false;
this.isComparePaused = false;
this.compareViz1 = null;
this.compareViz2 = null;
this.sizeUpdateTimeout = null; // For debouncing size updates
this.init();
}
init() {
this.generateArray();
this.bindEvents();
this.updateButtonStates(); // Initialize button states
}
bindEvents() {
const sizeSlider = document.getElementById('arraySize');
const speedSlider = document.getElementById('sortSpeed');
const shuffleBtn = document.getElementById('shuffleArray');
const startBtn = document.getElementById('startSort');
const pauseResumeBtn = document.getElementById('pauseResumeSort');
const stopBtn = document.getElementById('stopSort');
if (sizeSlider) {
// Update display immediately on input
sizeSlider.addEventListener('input', (e) => {
const newSize = parseInt(e.target.value, 10);
const sizeValueEl = document.getElementById('arraySizeValue');
if (sizeValueEl && !isNaN(newSize) && newSize >= 10 && newSize <= 9999) {
sizeValueEl.textContent = newSize;
}
});
// Debounce the actual array generation on change
sizeSlider.addEventListener('change', (e) => {
try {
const newSize = parseInt(e.target.value, 10);
const sizeValueEl = document.getElementById('arraySizeValue');
// Validate size value
if (!isNaN(newSize) && newSize >= 10 && newSize <= 9999) {
// Clear any pending timeout
if (this.sizeUpdateTimeout) {
clearTimeout(this.sizeUpdateTimeout);
}
// Debounce the array generation
this.sizeUpdateTimeout = setTimeout(() => {
// Only update if not in comparison mode or if regular visualization is visible
const regularViz = document.getElementById('regularVisualization');
if (!this.isCompareMode || (regularViz && regularViz.style.display !== 'none')) {
this.size = newSize;
if (sizeValueEl) {
sizeValueEl.textContent = this.size;
}
this.updateSizePresets();
// Only generate if container exists and is visible
if (this.container && this.container.offsetParent !== null) {
this.generateArray();
}
}
}, 150); // 150ms debounce
}
} catch (error) {
console.error('Error updating array size:', error);
// Reset to default if error occurs
this.size = 30;
const sizeValueEl = document.getElementById('arraySizeValue');
if (sizeValueEl) {
sizeValueEl.textContent = '30';
}
if (sizeSlider) {
sizeSlider.value = 30;
}
}
});
}
// Size preset buttons - only bind to sorting section presets
const sortingSection = document.getElementById('sorting');
if (sortingSection) {
sortingSection.querySelectorAll('.btn-preset[data-size]').forEach(btn => {
btn.addEventListener('click', () => {
try {
const size = parseInt(btn.dataset.size, 10);
if (!isNaN(size) && size >= 10 && size <= 9999) {
this.size = size;
if (sizeSlider) {
sizeSlider.value = size;
}
const sizeValueEl = document.getElementById('arraySizeValue');
if (sizeValueEl) {
sizeValueEl.textContent = size;
}
this.updateSizePresets();
this.generateArray();
}
} catch (error) {
console.error('Error setting preset size:', error);
}
});
});
}
// Comparison mode toggle
const toggleCompareBtn = document.getElementById('toggleCompare');
const compareControls = document.getElementById('compareControls');
const compareContainer = document.getElementById('compareContainer');
const startCompareBtn = document.getElementById('startCompare');
if (toggleCompareBtn) {
toggleCompareBtn.addEventListener('click', () => {
this.isCompareMode = !this.isCompareMode;
const regularViz = document.getElementById('regularVisualization');
if (this.isCompareMode) {
this.stopComparison(); // Stop any running comparison
compareControls.style.display = 'block';
compareContainer.style.display = 'grid';
if (regularViz) regularViz.style.display = 'none';
toggleCompareBtn.textContent = '❌ Exit Compare';
toggleCompareBtn.classList.add('active');
} else {
this.stopComparison(); // Stop any running comparison
compareControls.style.display = 'none';
compareContainer.style.display = 'none';
if (regularViz) regularViz.style.display = 'block';
toggleCompareBtn.textContent = '⚔️ Compare';
toggleCompareBtn.classList.remove('active');
}
});
}
if (startCompareBtn) {
startCompareBtn.addEventListener('click', () => this.startComparison());
}
// Comparison mode pause/resume and stop buttons
const pauseResumeCompareBtn = document.getElementById('pauseResumeCompare');
const stopCompareBtn = document.getElementById('stopCompare');
if (pauseResumeCompareBtn) {
pauseResumeCompareBtn.addEventListener('click', () => this.togglePauseResumeCompare());
}
if (stopCompareBtn) {
stopCompareBtn.addEventListener('click', () => this.stopComparison());
}
if (speedSlider) {
const multiplierEl = document.getElementById('sortSpeedMultiplier');
if (multiplierEl) {
// Initialize multiplier display
const initialMultiplier = Math.round((this.speed / 50) * 10) / 10;
multiplierEl.textContent = `${initialMultiplier}x`;
}
speedSlider.addEventListener('input', (e) => {
try {
const newSpeed = parseInt(e.target.value, 10);
// Validate speed value - allow up to 250 (5x speed)
// For arrays > 500, allow higher speeds (up to 5x)
const maxSpeed = this.size > 500 ? 250 : 150; // 5x for large arrays, 3x for smaller
const actualMaxSpeed = Math.min(250, maxSpeed);
if (!isNaN(newSpeed) && newSpeed >= 25 && newSpeed <= actualMaxSpeed) {
this.speed = newSpeed;
if (multiplierEl) {
const multiplier = Math.round((this.speed / 50) * 10) / 10;
multiplierEl.textContent = `${multiplier}x`;
}
} else if (newSpeed > actualMaxSpeed) {
// Clamp to max speed
this.speed = actualMaxSpeed;
speedSlider.value = actualMaxSpeed;
if (multiplierEl) {
const multiplier = Math.round((this.speed / 50) * 10) / 10;
multiplierEl.textContent = `${multiplier}x`;
}
}
} catch (error) {
console.error('Error updating speed:', error);
// Reset to default if error occurs
this.speed = 50;
if (multiplierEl) {
multiplierEl.textContent = '1x';
}
}
});
// Update max speed when array size changes
const updateMaxSpeed = () => {
const maxSpeed = this.size > 500 ? 250 : 150;
speedSlider.max = maxSpeed;
};
// Listen for size changes
const sizeSlider = document.getElementById('arraySize');
if (sizeSlider) {
sizeSlider.addEventListener('change', updateMaxSpeed);
}
// Update on preset button clicks
document.querySelectorAll('.btn-preset[data-size]').forEach(btn => {
btn.addEventListener('click', updateMaxSpeed);
});
}
if (shuffleBtn) shuffleBtn.addEventListener('click', () => this.generateArray());
if (startBtn) startBtn.addEventListener('click', () => this.start());
if (pauseResumeBtn) pauseResumeBtn.addEventListener('click', () => this.togglePauseResume());
if (stopBtn) stopBtn.addEventListener('click', () => this.stop());
}
updateButtonStates() {
const startBtn = document.getElementById('startSort');
const pauseResumeBtn = document.getElementById('pauseResumeSort');
const stopBtn = document.getElementById('stopSort');
if (this.isRunning) {
if (startBtn) {
startBtn.style.visibility = 'hidden';
startBtn.style.position = 'absolute';
startBtn.style.opacity = '0';
startBtn.style.pointerEvents = 'none';
}
if (pauseResumeBtn) {
pauseResumeBtn.style.visibility = 'visible';
pauseResumeBtn.style.position = 'static';
pauseResumeBtn.style.opacity = '1';
pauseResumeBtn.style.pointerEvents = 'auto';
pauseResumeBtn.textContent = this.isPaused ? '▶ Resume' : '⏸ Pause';
}
if (stopBtn) {
stopBtn.style.visibility = 'visible';
stopBtn.style.position = 'static';
stopBtn.style.opacity = '1';
stopBtn.style.pointerEvents = 'auto';
}
} else {
if (startBtn) {
startBtn.style.visibility = 'visible';
startBtn.style.position = 'static';
startBtn.style.opacity = '1';
startBtn.style.pointerEvents = 'auto';
}
if (pauseResumeBtn) {
pauseResumeBtn.style.visibility = 'hidden';
pauseResumeBtn.style.position = 'absolute';
pauseResumeBtn.style.opacity = '0';
pauseResumeBtn.style.pointerEvents = 'none';
}
if (stopBtn) {
stopBtn.style.visibility = 'hidden';
stopBtn.style.position = 'absolute';
stopBtn.style.opacity = '0';
stopBtn.style.pointerEvents = 'none';
}
}
}
togglePauseResume() {
if (this.isPaused) {
this.resume();
} else {
this.pause();
}
}
pause() {
if (!this.isRunning || this.isPaused) return;
this.isPaused = true;
// Save pause time to account for elapsed time
if (this.startTime) {
this.pausedTime += performance.now() - this.startTime;
}
this.updateButtonStates();
}
resume() {
if (!this.isPaused || !this.isRunning) return;
this.isPaused = false;
// Restart timing (pausedTime already accumulated in pause())
this.startTime = performance.now();
this.updateButtonStates();
// The algorithm will continue naturally from the delay() function
}
updateSizePresets() {
document.querySelectorAll('.btn-preset').forEach(btn => {
const presetSize = parseInt(btn.dataset.size);
if (presetSize === this.size) {
btn.classList.add('active');
} else {
btn.classList.remove('active');
}
});
}
generateArray() {
// Don't generate if in comparison mode and regular viz is hidden
if (this.isCompareMode) {
const regularViz = document.getElementById('regularVisualization');
if (regularViz && regularViz.style.display === 'none') {
return; // Don't update regular visualization when in comparison mode
}
}
this.stop();
// Validate size before generating
if (this.size < 10 || this.size > 9999 || isNaN(this.size)) {
this.size = 30;
}
this.array = Array.from({ length: this.size }, () => Math.floor(Math.random() * 100) + 1);
// Only render if container exists and is visible
if (this.container && this.container.offsetParent !== null) {
this.render();
}
this.resetStats();
this.updateButtonStates();
}
render(comparing = [], swapping = [], sorted = [], container = null) {
const targetContainer = container || this.container;
if (!targetContainer) return;
// Safety check: ensure container is in DOM and visible
if (!targetContainer.parentNode || targetContainer.offsetParent === null) {
return;
}
// Validate array exists and has valid length
if (!this.array || this.array.length === 0) {
return;
}
// For large arrays (>1000), use sampling for performance
const shouldSample = this.array.length > 1000;
const sampleSize = shouldSample ? 1000 : this.array.length;
const step = shouldSample ? Math.ceil(this.array.length / sampleSize) : 1;
// Use requestAnimationFrame for smoother rendering and to ensure container is measured
requestAnimationFrame(() => {
try {
// Clear container completely to remove any lingering visual states
targetContainer.innerHTML = '';
const maxVal = Math.max(...this.array);
if (maxVal === 0 || isNaN(maxVal)) {
return; // Invalid array values
}
// Calculate bar width after container is in DOM and visible
const gap = 2; // gap between bars in pixels
const containerPadding = 32; // approximate padding
const containerWidth = targetContainer.clientWidth || targetContainer.offsetWidth || 800; // fallback to 800px
const availableWidth = Math.max(100, containerWidth - containerPadding);
const totalBars = shouldSample ? sampleSize : this.array.length;
// Calculate bar width to fit container, but ensure visibility
// For arrays <= 200: bars fill container (flex)
// For arrays > 200: calculate width, minimum 2px for visibility, allow horizontal scrolling
let barWidth = null;
let useFlex = false;
if (this.array.length <= 200) {
// Small arrays: use flex to fill container
useFlex = true;
} else {
// Large arrays: calculate width to fit container, but ensure minimum 2px for visibility
const calculatedWidth = (availableWidth / totalBars) - gap;
// Minimum 2px width for visibility, maximum 30px for aesthetics
barWidth = Math.max(2, Math.min(calculatedWidth, 30));
// If bars would be too small, ensure they're at least 2px and container will scroll
// This ensures all bars are visible when scrolling
if (calculatedWidth < 2) {
barWidth = 2;
}
}
for (let i = 0; i < this.array.length; i += step) {
const val = this.array[i];
if (isNaN(val)) continue; // Skip invalid values
const bar = document.createElement('div');
bar.className = 'bar';
bar.style.height = `${(val / maxVal) * 100}%`;
// Set width based on array size
if (useFlex) {
// Small arrays: use flex to fill container
bar.style.flex = '1 1 auto';
bar.style.minWidth = '0';
} else if (barWidth !== null) {
// Large arrays: explicit width to ensure visibility and scrolling
bar.style.width = `${barWidth}px`;
bar.style.minWidth = `${barWidth}px`;
bar.style.maxWidth = `${barWidth}px`;
bar.style.flexShrink = '0';
bar.style.flexGrow = '0';
} else if (shouldSample) {
bar.style.width = `${step * 100 / sampleSize}%`;
}
// Apply visual states - only one state per bar (sorted > swapping > comparing)
if (sorted.includes(i)) {
bar.classList.add('sorted');
} else if (swapping.includes(i)) {
bar.classList.add('swapping');
} else if (comparing.includes(i)) {
bar.classList.add('comparing');
}
targetContainer.appendChild(bar);
}
} catch (error) {
console.error('Error rendering array:', error);
}
});
}
resetStats() {
this.comparisons = 0;
this.swaps = 0;
this.updateStat('comparisons', '0');
this.updateStat('swaps', '0');
this.updateStat('sortTime', '0ms');
}
updateStat(id, value) {
const el = document.getElementById(id);
if (el) el.textContent = value;
}
stop() {
this.shouldStop = true;
this.isRunning = false;
this.isPaused = false;
this.pausedTime = 0;
// Reset visual state when stopped
this.render(); // Clear any highlighting/comparing/swapping states
this.updateButtonStates();
}
async start() {
if (this.isRunning && !this.isPaused) return;
// If resuming from pause, just resume
if (this.isPaused) {
this.resume();
return;
}
// Starting fresh
this.isRunning = true;
this.isPaused = false;
this.shouldStop = false;
this.pausedTime = 0;
this.resetStats();
this.updateButtonStates();
if (typeof audioEngine !== 'undefined') audioEngine.playBattleStart();
this.startTime = performance.now();
switch (this.currentAlgorithm) {
case 'bubbleSort': await this.bubbleSort(); break;
case 'quickSort': await this.quickSort(0, this.array.length - 1); break;
case 'mergeSort': await this.mergeSortWrapper(); break;
case 'insertionSort': await this.insertionSort(); break;
case 'selectionSort': await this.selectionSort(); break;
case 'heapSort': await this.heapSort(); break;
case 'countingSort': await this.countingSort(); break;
case 'radixSort': await this.radixSort(); break;
case 'shellSort': await this.shellSort(); break;
case 'timSort': await this.timSort(); break;
case 'bucketSort': await this.bucketSort(); break;
case 'cocktailSort': await this.cocktailSort(); break;
case 'combSort': await this.combSort(); break;
case 'cycleSort': await this.cycleSort(); break;
case 'gnomeSort': await this.gnomeSort(); break;
case 'pancakeSort': await this.pancakeSort(); break;
default: await this.bubbleSort();
}
if (!this.shouldStop && !this.isPaused) {
const endTime = performance.now();
const elapsed = endTime - this.startTime + this.pausedTime;
rawTimeValues.sortTime = elapsed;
const formatSelect = document.getElementById('sortTimeFormat');
let format = formatSelect ? formatSelect.value : 'ms';
if (elapsed >= 2000) {
const bestFormat = getBestTimeFormat(elapsed);
format = bestFormat;
if (formatSelect) formatSelect.value = bestFormat;
}
this.updateStat('sortTime', formatTimeValue(elapsed, format));
this.render([], [], Array.from({ length: this.array.length }, (_, i) => i));
if (typeof audioEngine !== 'undefined') audioEngine.playComplete();
}
if (!this.isPaused) {
this.isRunning = false;
this.pausedTime = 0;
this.updateButtonStates();
// Show feedback modal after algorithm completion
if (typeof showFeedbackModal === 'function') {
setTimeout(() => showFeedbackModal(), 1000); // Delay 1 second after completion
}
}
}
async startComparison() {
if (this.isCompareRunning && !this.isComparePaused) return;
if (this.isComparePaused) {
this.resumeComparison();
return;
}
const algo1 = document.getElementById('compareAlgo1').value;
const algo2 = document.getElementById('compareAlgo2').value;
const lang1 = document.getElementById('compareLang1').value;
const lang2 = document.getElementById('compareLang2').value;
if (algo1 === algo2 && lang1 === lang2) {
alert('Please select different algorithms or languages to compare!');
return;
}
this.isCompareRunning = true;
this.isComparePaused = false;
this.shouldStop = false;
// Update button states
this.updateCompareButtonStates();
// Generate the same array for both algorithms
const testArray = Array.from({ length: this.size }, () => Math.floor(Math.random() * 100) + 1);
// Create copies for each algorithm
const array1 = [...testArray];
const array2 = [...testArray];
// Update algorithm names with language
const langInfo = getLanguageInfo();
const lang1Name = langInfo[lang1]?.name || lang1;
const lang2Name = langInfo[lang2]?.name || lang2;
document.getElementById('compareAlgo1Name').textContent = `${this.getAlgorithmName(algo1)} (${lang1Name})`;
document.getElementById('compareAlgo2Name').textContent = `${this.getAlgorithmName(algo2)} (${lang2Name})`;
// Reset stats
document.getElementById('comparisons1').textContent = '0';
document.getElementById('swaps1').textContent = '0';
document.getElementById('sortTime1').textContent = '0ms';
document.getElementById('comparisons2').textContent = '0';
document.getElementById('swaps2').textContent = '0';
document.getElementById('sortTime2').textContent = '0ms';
// Run both algorithms in parallel
const container1 = document.getElementById('sortingBars1');
const container2 = document.getElementById('sortingBars2');
// Render initial arrays
this.renderArray(array1, container1);
this.renderArray(array2, container2);
// Run comparisons with language speed factors
const [result1, result2] = await Promise.all([
this.runAlgorithmForComparison(algo1, lang1, array1, container1, 1),
this.runAlgorithmForComparison(algo2, lang2, array2, container2, 2)
]);
// Display winner
this.displayComparisonResults(result1, result2);
this.isCompareRunning = false;
this.updateCompareButtonStates();
// Show feedback modal after comparison completion
if (typeof showFeedbackModal === 'function') {
setTimeout(() => showFeedbackModal(), 1000); // Delay 1 second after completion
}
}
stopComparison() {
this.shouldStop = true;
this.isCompareRunning = false;
this.isComparePaused = false;
if (this.compareViz1) this.compareViz1.shouldStop = true;
if (this.compareViz2) this.compareViz2.shouldStop = true;
this.updateCompareButtonStates();
}
togglePauseResumeCompare() {
if (this.isComparePaused) {
this.resumeComparison();
} else {
this.pauseComparison();
}
}
pauseComparison() {
if (!this.isCompareRunning || this.isComparePaused) return;
this.isComparePaused = true;
if (this.compareViz1) this.compareViz1.isPaused = true;
if (this.compareViz2) this.compareViz2.isPaused = true;
this.updateCompareButtonStates();
}
resumeComparison() {
if (!this.isComparePaused || !this.isCompareRunning) return;
this.isComparePaused = false;
if (this.compareViz1) this.compareViz1.isPaused = false;
if (this.compareViz2) this.compareViz2.isPaused = false;
this.updateCompareButtonStates();
}
updateCompareButtonStates() {
const startBtn = document.getElementById('startCompare');
const pauseResumeBtn = document.getElementById('pauseResumeCompare');
const stopBtn = document.getElementById('stopCompare');
if (this.isCompareRunning) {
if (startBtn) {
startBtn.style.visibility = 'hidden';
startBtn.style.position = 'absolute';
startBtn.style.opacity = '0';
startBtn.style.pointerEvents = 'none';
}
if (pauseResumeBtn) {
pauseResumeBtn.style.visibility = 'visible';
pauseResumeBtn.style.position = 'static';
pauseResumeBtn.style.opacity = '1';
pauseResumeBtn.style.pointerEvents = 'auto';
pauseResumeBtn.textContent = this.isComparePaused ? '▶ Resume' : '⏸ Pause';
}
if (stopBtn) {
stopBtn.style.visibility = 'visible';
stopBtn.style.position = 'static';
stopBtn.style.opacity = '1';
stopBtn.style.pointerEvents = 'auto';
}
} else {
if (startBtn) {
startBtn.style.visibility = 'visible';
startBtn.style.position = 'static';
startBtn.style.opacity = '1';
startBtn.style.pointerEvents = 'auto';
}
if (pauseResumeBtn) {
pauseResumeBtn.style.visibility = 'hidden';
pauseResumeBtn.style.position = 'absolute';
pauseResumeBtn.style.opacity = '0';
pauseResumeBtn.style.pointerEvents = 'none';
}
if (stopBtn) {
stopBtn.style.visibility = 'hidden';
stopBtn.style.position = 'absolute';
stopBtn.style.opacity = '0';
stopBtn.style.pointerEvents = 'none';
}
}
}
getAlgorithmName(algoKey) {
const names = {
'bubbleSort': 'Bubble Sort',
'quickSort': 'Quick Sort',
'mergeSort': 'Merge Sort',
'insertionSort': 'Insertion Sort',
'selectionSort': 'Selection Sort',
'heapSort': 'Heap Sort'
};
return names[algoKey] || algoKey;
}
renderArray(arr, container) {
if (!container || !arr || arr.length === 0) return;
// Use requestAnimationFrame to ensure container is measured
requestAnimationFrame(() => {
try {
container.innerHTML = '';
const maxVal = Math.max(...arr);
if (maxVal === 0 || isNaN(maxVal)) return;
const shouldSample = arr.length > 1000;
const sampleSize = shouldSample ? 1000 : arr.length;
const step = shouldSample ? Math.ceil(arr.length / sampleSize) : 1;
// Calculate bar width after container is in DOM and visible
const gap = 2;
const containerPadding = 32;
const containerWidth = container.clientWidth || container.offsetWidth || 800;
const availableWidth = Math.max(100, containerWidth - containerPadding);
const totalBars = shouldSample ? sampleSize : arr.length;
// Calculate bar width to fit container
let barWidth = null;
let useFlex = false;
if (arr.length <= 200) {
useFlex = true;
} else {
const calculatedWidth = (availableWidth / totalBars) - gap;
barWidth = Math.max(1, Math.min(calculatedWidth, 30));
if (barWidth < 2) {
barWidth = 2;
}
}
for (let i = 0; i < arr.length; i += step) {
const val = arr[i];
if (isNaN(val)) continue;
const bar = document.createElement('div');
bar.className = 'bar';
bar.style.height = `${(val / maxVal) * 100}%`;