-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2277 lines (2013 loc) · 66.2 KB
/
Copy pathscript.js
File metadata and controls
2277 lines (2013 loc) · 66.2 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
/* ============================================================
Sorting Algorithm Lab v4
Vanilla JS — no frameworks
============================================================ */
const ALGORITHM_IDS = [
"bubble", "selection", "insertion", "merge", "quick", "heap", "shell", "radix",
"counting", "cocktail",
];
// ---------- Algorithm metadata ----------
const ALGORITHM_PROFILES = {
bubble: {
name: "Bubble Sort",
best: "O(n)",
avg: "O(n²)",
worst: "O(n²)",
stable: true,
inPlace: true,
memory: "O(1)",
description: "Repeatedly swaps adjacent out-of-order pairs until sorted.",
},
selection: {
name: "Selection Sort",
best: "O(n²)",
avg: "O(n²)",
worst: "O(n²)",
stable: false,
inPlace: true,
memory: "O(1)",
description: "Finds the minimum in the unsorted region and swaps it to the front.",
},
insertion: {
name: "Insertion Sort",
best: "O(n)",
avg: "O(n²)",
worst: "O(n²)",
stable: true,
inPlace: true,
memory: "O(1)",
description: "Builds a sorted prefix by inserting each element into place.",
},
merge: {
name: "Merge Sort",
best: "O(n log n)",
avg: "O(n log n)",
worst: "O(n log n)",
stable: true,
inPlace: false,
memory: "O(n)",
description: "Divide-and-conquer merge of sorted halves using auxiliary storage.",
},
quick: {
name: "Quick Sort",
best: "O(n log n)",
avg: "O(n log n)",
worst: "O(n²)",
stable: false,
inPlace: true,
memory: "O(log n)",
description: "Partitions around a pivot, then recursively sorts sub-arrays.",
},
heap: {
name: "Heap Sort",
best: "O(n log n)",
avg: "O(n log n)",
worst: "O(n log n)",
stable: false,
inPlace: true,
memory: "O(1)",
description: "Heapifies the array, then repeatedly extracts the maximum.",
},
shell: {
name: "Shell Sort",
best: "O(n log n)",
avg: "O(n^4/3)",
worst: "O(n²)",
stable: false,
inPlace: true,
memory: "O(1)",
description: "Insertion sort with diminishing gaps — compares distant pairs first.",
},
radix: {
name: "Radix Sort",
best: "O(nk)",
avg: "O(nk)",
worst: "O(nk)",
stable: true,
inPlace: false,
memory: "O(n + k)",
description: "Sorts by individual digits using counting sort passes (LSD).",
},
counting: {
name: "Counting Sort",
best: "O(n + k)",
avg: "O(n + k)",
worst: "O(n + k)",
stable: true,
inPlace: false,
memory: "O(k)",
description: "Counts occurrences of each value, then reconstructs the sorted array.",
},
cocktail: {
name: "Cocktail Shaker Sort",
best: "O(n)",
avg: "O(n²)",
worst: "O(n²)",
stable: true,
inPlace: true,
memory: "O(1)",
description: "Bidirectional bubble sort — sweeps forward then backward each pass.",
},
};
const LEARNING_CARDS = {
bubble: {
trivia: "Bubble sort is one of the simplest algorithms taught in CS101 — yet it inspired early GPU sorting research.",
useCase: "Educational demos and tiny embedded lists where code size matters more than speed.",
},
selection: {
trivia: "Selection sort always makes exactly n−1 swaps, no matter the input order.",
useCase: "Flash memory systems where writes are expensive and minimizing swaps is critical.",
},
insertion: {
trivia: "Insertion sort is the algorithm behind Timsort's galloping merge for nearly-sorted runs.",
useCase: "Real-time online sorting — e.g. sorting a hand of playing cards as you receive them.",
},
merge: {
trivia: "Merge sort was invented by John von Neumann in 1945 for the EDVAC computer.",
useCase: "External sorting of massive datasets that don't fit in RAM (database indexes, log files).",
},
quick: {
trivia: "Tony Hoare invented Quick Sort at age 26 while on an exchange program in Moscow.",
useCase: "General-purpose in-memory sorting — used in C's qsort, Python's Timsort hybrid, and more.",
},
heap: {
trivia: "Heap sort guarantees O(n log n) without extra arrays — unlike merge sort.",
useCase: "Priority queues and real-time systems needing predictable worst-case performance.",
},
shell: {
trivia: "Donald Shell published Shell Sort in 1959 — it was the first algorithm to beat O(n²) in practice.",
useCase: "Medium-sized in-memory arrays where simplicity beats merge sort's overhead.",
},
radix: {
trivia: "Radix sort can sort integers faster than comparison-based sorts when the key range is bounded.",
useCase: "Sorting fixed-width integers — IP addresses, zip codes, and database column indexes.",
},
counting: {
trivia: "Counting sort is not comparison-based — it sidesteps the O(n log n) lower bound entirely.",
useCase: "Sorting exam scores (0–100), histograms, and vote tallies with a small value range.",
},
cocktail: {
trivia: "Cocktail shaker sort is also called bidirectional bubble sort or shaker sort.",
useCase: "Teaching bidirectional scanning — slightly better than bubble on reversed arrays.",
},
};
const DATASET_LABELS = {
random: "Random",
sorted: "Sorted",
"nearly-sorted": "Nearly Sorted",
reversed: "Reversed",
"few-unique": "Few Unique",
sawtooth: "Sawtooth",
custom: "Custom Input",
};
const HISTORY_KEY = "sortLabHistory";
const QUIZ_SCORE_KEY = "sortLabQuizScore";
const MAX_HISTORY = 8;
// ---------- DOM references ----------
const $ = (id) => document.getElementById(id);
const dom = {
algorithm: $("algorithm"),
algorithmRace: $("algorithmRace"),
dataset: $("dataset"),
size: $("size"),
speed: $("speed"),
sizeValue: $("sizeValue"),
speedValue: $("speedValue"),
raceMode: $("raceMode"),
stepMode: $("stepMode"),
teachingMode: $("teachingMode"),
soundToggle: $("soundToggle"),
themeToggle: $("themeToggle"),
customArrayField: $("customArrayField"),
customArray: $("customArray"),
applyCustomBtn: $("applyCustomBtn"),
customArrayError: $("customArrayError"),
generateBtn: $("generateBtn"),
startBtn: $("startBtn"),
pauseBtn: $("pauseBtn"),
stopBtn: $("stopBtn"),
nextStepBtn: $("nextStepBtn"),
resetBtn: $("resetBtn"),
tournamentBtn: $("tournamentBtn"),
exportCsvBtn: $("exportCsvBtn"),
copySummaryBtn: $("copySummaryBtn"),
visualizer: $("visualizer"),
visualizerRace: $("visualizerRace"),
panePrimary: $("panePrimary"),
paneSecondary: $("paneSecondary"),
metricsPrimary: $("metricsPrimary"),
metricsSecondary: $("metricsSecondary"),
profilePanel: $("profilePanel"),
historyList: $("historyList"),
legend: $("legend"),
statusText: $("statusText"),
toast: $("toast"),
teachingPanel: $("teachingPanel"),
teachingText: $("teachingText"),
opsChart: $("opsChart"),
tournamentPanel: $("tournamentPanel"),
leaderboard: $("leaderboard"),
comparisonPanel: $("comparisonPanel"),
comparisonMatrix: $("comparisonMatrix"),
a11yAnnouncer: $("a11yAnnouncer"),
shareUrlBtn: $("shareUrlBtn"),
presentationBtn: $("presentationBtn"),
quizMode: $("quizMode"),
quizScore: $("quizScore"),
quizPanel: $("quizPanel"),
quizGuessGrid: $("quizGuessGrid"),
quizFeedback: $("quizFeedback"),
recommenderContent: $("recommenderContent"),
learningCard: $("learningCard"),
learningTrivia: $("learningTrivia"),
learningUseCase: $("learningUseCase"),
heatmapPrimary: $("heatmapPrimary"),
heatmapSecondary: $("heatmapSecondary"),
countingArrayPanel: $("countingArrayPanel"),
countingArrayDisplay: $("countingArrayDisplay"),
panePrimaryLabel: $("panePrimaryLabel"),
presentationOverlay: $("presentationOverlay"),
presentationAlgo: $("presentationAlgo"),
presentationMetrics: $("presentationMetrics"),
presentationExitBtn: $("presentationExitBtn"),
presentationVisualizer: $("presentationVisualizer"),
presentationHeatmap: $("presentationHeatmap"),
};
// ---------- Dataset analysis & recommender ----------
function analyzeDataset(arr) {
const n = arr.length;
const unique = new Set(arr).size;
let inversions = 0;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) inversions++;
}
}
const maxInversions = (n * (n - 1)) / 2 || 1;
const sortedness = 1 - inversions / maxInversions;
const min = Math.min(...arr);
const max = Math.max(...arr);
const range = max - min + 1;
return { n, unique, inversions, sortedness, uniqueRatio: unique / n, min, max, range };
}
function recommendAlgorithm(arr) {
const stats = analyzeDataset(arr);
if (stats.sortedness > 0.92) {
return {
algorithm: "insertion",
reason: `Dataset is ${Math.round(stats.sortedness * 100)}% sorted — Insertion Sort runs in near O(n) time on already-ordered data.`,
stats,
};
}
if (stats.unique <= 12 && stats.range <= 100 && stats.n >= 15) {
return {
algorithm: "counting",
reason: `Only ${stats.unique} distinct values in a range of ${stats.range} — Counting Sort avoids comparisons entirely.`,
stats,
};
}
if (stats.uniqueRatio < 0.2 && stats.n >= 20) {
return {
algorithm: "radix",
reason: `Low cardinality (${stats.unique} unique / ${stats.n} elements) — Radix Sort distributes by digits efficiently.`,
stats,
};
}
if (stats.sortedness < 0.15) {
return {
algorithm: "merge",
reason: "Highly disordered (likely reversed) — Merge Sort guarantees O(n log n) regardless of input order.",
stats,
};
}
if (stats.n <= 25) {
return {
algorithm: "insertion",
reason: `Small array (n=${stats.n}) — Insertion Sort has low overhead and excellent cache locality.`,
stats,
};
}
return {
algorithm: "quick",
reason: "General-purpose random data — Quick Sort offers excellent average-case performance in practice.",
stats,
};
}
function heatmapColor(ratio) {
const low = getComputedStyle(document.documentElement).getPropertyValue("--heatmap-low").trim() || "#dbeafe";
const high = getComputedStyle(document.documentElement).getPropertyValue("--heatmap-high").trim() || "#dc2626";
const parse = (hex) => {
const h = hex.replace("#", "");
return [
parseInt(h.slice(0, 2), 16),
parseInt(h.slice(2, 4), 16),
parseInt(h.slice(4, 6), 16),
];
};
const [r1, g1, b1] = parse(low.length === 7 ? low : "#dbeafe");
const [r2, g2, b2] = parse(high.length === 7 ? high : "#dc2626");
const t = Math.min(1, Math.max(0, ratio));
const r = Math.round(r1 + (r2 - r1) * t);
const g = Math.round(g1 + (g2 - g1) * t);
const b = Math.round(b1 + (b2 - b1) * t);
return `rgb(${r}, ${g}, ${b})`;
}
// ---------- Dataset generators ----------
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function valueFromIndex(i, size) {
return Math.floor(((i + 1) / size) * 90) + 5;
}
function generateDataset(type, size) {
switch (type) {
case "sorted":
return Array.from({ length: size }, (_, i) => valueFromIndex(i, size));
case "reversed":
return Array.from({ length: size }, (_, i) => valueFromIndex(size - 1 - i, size));
case "nearly-sorted": {
const arr = Array.from({ length: size }, (_, i) => valueFromIndex(i, size));
const swaps = Math.max(1, Math.floor(size * 0.05));
for (let s = 0; s < swaps; s++) {
const a = randomInt(0, size - 1);
const b = randomInt(0, size - 1);
[arr[a], arr[b]] = [arr[b], arr[a]];
}
return arr;
}
case "few-unique": {
const uniques = [12, 28, 44, 60, 76, 92];
return Array.from({ length: size }, () => uniques[randomInt(0, uniques.length - 1)]);
}
case "sawtooth": {
const period = Math.max(4, Math.floor(size / 6));
return Array.from({ length: size }, (_, i) => {
const phase = i % period;
const ascending = phase < period / 2;
const pos = ascending ? phase : period - phase;
return Math.floor((pos / (period / 2)) * 85) + 10;
});
}
case "random":
default:
return Array.from({ length: size }, () => randomInt(5, 95));
}
}
function parseCustomArray(input, maxSize = 120) {
const trimmed = input.trim();
if (!trimmed) {
return { error: "Enter comma-separated values or a JSON array." };
}
let values;
try {
if (trimmed.startsWith("[")) {
values = JSON.parse(trimmed);
if (!Array.isArray(values)) {
return { error: "JSON input must be an array." };
}
} else {
values = trimmed.split(/[,\s]+/).filter(Boolean).map(Number);
}
} catch {
return { error: "Invalid JSON array format." };
}
if (!values.length) {
return { error: "Array must contain at least one number." };
}
if (values.length > maxSize) {
return { error: `Maximum ${maxSize} elements allowed.` };
}
if (values.some((v) => typeof v !== "number" || !Number.isFinite(v))) {
return { error: "All values must be valid numbers." };
}
const min = Math.min(...values);
const max = Math.max(...values);
const range = max - min || 1;
const normalized = values.map((v) => Math.round(((v - min) / range) * 85 + 10));
return { data: normalized, original: values };
}
// ---------- Operations sparkline chart ----------
class OperationsChart {
constructor(canvas) {
this.canvas = canvas;
this.ctx = canvas ? canvas.getContext("2d") : null;
this.points = [];
if (canvas) {
this.resize();
window.addEventListener("resize", () => this.resize());
}
}
resize() {
if (!this.canvas || !this.ctx) return;
const wrap = this.canvas.parentElement;
const w = Math.max(120, wrap.clientWidth - 110);
const dpr = window.devicePixelRatio || 1;
this.canvas.width = Math.floor(w * dpr);
this.canvas.height = Math.floor(56 * dpr);
this.canvas.style.width = `${w}px`;
this.canvas.style.height = "56px";
this.ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
this.draw();
}
reset() {
this.points = [];
this.draw();
}
push(totalOps) {
this.points.push(totalOps);
if (this.points.length > 600) this.points.shift();
this.draw();
}
draw() {
if (!this.ctx || !this.canvas) return;
const w = this.canvas.width / (window.devicePixelRatio || 1);
const h = 56;
this.ctx.clearRect(0, 0, w, h);
if (this.points.length < 2) return;
const max = Math.max(...this.points, 1);
const pad = 4;
const innerW = w - pad * 2;
const innerH = h - pad * 2;
const color = getComputedStyle(document.documentElement)
.getPropertyValue("--primary")
.trim() || "#2563eb";
this.ctx.strokeStyle = color;
this.ctx.lineWidth = 2;
this.ctx.beginPath();
this.points.forEach((val, i) => {
const x = pad + (i / (this.points.length - 1)) * innerW;
const y = pad + innerH - (val / max) * innerH;
if (i === 0) this.ctx.moveTo(x, y);
else this.ctx.lineTo(x, y);
});
this.ctx.stroke();
this.ctx.lineTo(pad + innerW, pad + innerH);
this.ctx.lineTo(pad, pad + innerH);
this.ctx.closePath();
this.ctx.fillStyle = color.includes("rgb") ? color.replace(")", ", 0.12)").replace("rgb", "rgba") : "rgba(37, 99, 235, 0.12)";
this.ctx.fill();
}
}
// ---------- Audio ----------
class AudioManager {
constructor() {
this.enabled = localStorage.getItem("sound") === "true";
this.ctx = null;
}
init() {
if (!this.ctx) {
this.ctx = new (window.AudioContext || window.webkitAudioContext)();
}
if (this.ctx.state === "suspended") {
this.ctx.resume();
}
}
beep(frequency = 440, duration = 0.03, volume = 0.04) {
if (!this.enabled) return;
this.init();
const osc = this.ctx.createOscillator();
const gain = this.ctx.createGain();
osc.type = "sine";
osc.frequency.value = frequency;
gain.gain.value = volume;
osc.connect(gain);
gain.connect(this.ctx.destination);
osc.start();
osc.stop(this.ctx.currentTime + duration);
}
compare() {
this.beep(520, 0.02, 0.03);
}
swap() {
this.beep(280, 0.04, 0.05);
}
write() {
this.beep(400, 0.025, 0.035);
}
setEnabled(enabled) {
this.enabled = enabled;
localStorage.setItem("sound", String(enabled));
}
}
// ---------- Metrics ----------
class Metrics {
constructor() {
this.reset();
}
reset() {
this.comparisons = 0;
this.swaps = 0;
this.writes = 0;
this.startTime = 0;
this.elapsedMs = 0;
}
start() {
this.reset();
this.startTime = performance.now();
}
finish() {
this.elapsedMs = Math.round(performance.now() - this.startTime);
}
}
// ---------- Sort runner (one visualization pane) ----------
class SortRunner {
constructor({ container, metricsEl, heatmapEl, label }) {
this.container = container;
this.metricsEl = metricsEl;
this.heatmapEl = heatmapEl;
this.label = label;
this.array = [];
this.bars = [];
this.accessCounts = [];
this.metrics = new Metrics();
this.paused = false;
this.stopped = false;
this.stepMode = false;
this.silent = false;
this.teachingMode = false;
this.stepResolver = null;
this.isRunning = false;
this.audio = null;
this.speedSlider = null;
this.onNarrate = null;
this.onOperation = null;
this.onVisualUpdate = null;
this.onCountingArrayUpdate = null;
this.currentGap = 0;
this.currentDigitExp = 1;
}
configure({
audio,
speedSlider,
stepMode,
silent = false,
teachingMode = false,
onNarrate,
onOperation,
onVisualUpdate,
onCountingArrayUpdate,
}) {
this.audio = audio;
this.speedSlider = speedSlider;
this.stepMode = stepMode;
this.silent = silent;
this.teachingMode = teachingMode;
this.onNarrate = onNarrate || null;
this.onOperation = onOperation || null;
this.onVisualUpdate = onVisualUpdate || null;
this.onCountingArrayUpdate = onCountingArrayUpdate || null;
}
setArray(data) {
this.array = [...data];
this.accessCounts = new Array(data.length).fill(0);
this.renderBars();
this.renderHeatmap();
}
renderBars() {
if (this.silent) return;
this.container.innerHTML = "";
this.bars = this.array.map((value) => {
const bar = document.createElement("div");
bar.className = "bar";
bar.style.height = `${value}%`;
bar.setAttribute("role", "presentation");
this.container.appendChild(bar);
return bar;
});
}
clearStateClasses() {
this.bars.forEach((bar) => {
bar.classList.remove("compare", "swap", "sorted", "pivot", "write", "digit", "gap", "bucket");
});
}
trackAccess(...indices) {
indices.forEach((i) => {
if (i >= 0 && i < this.accessCounts.length) {
this.accessCounts[i]++;
}
});
}
renderHeatmap() {
if (!this.heatmapEl || this.silent) return;
const n = this.array.length;
if (this.heatmapEl.children.length !== n) {
this.heatmapEl.innerHTML = "";
for (let i = 0; i < n; i++) {
const cell = document.createElement("div");
cell.className = "heatmap-cell";
cell.title = `Index ${i}: 0 accesses`;
this.heatmapEl.appendChild(cell);
}
}
const max = Math.max(...this.accessCounts, 1);
Array.from(this.heatmapEl.children).forEach((cell, i) => {
const count = this.accessCounts[i] || 0;
cell.style.background = heatmapColor(count / max);
cell.title = `Index ${i}: ${count} access${count === 1 ? "" : "es"}`;
});
}
notifyVisualUpdate() {
this.renderHeatmap();
this.onVisualUpdate?.(this);
}
narrate(message) {
if (!this.teachingMode || this.silent || !this.onNarrate) return;
this.onNarrate(message);
}
recordOperation() {
if (this.silent || !this.onOperation) return;
const total = this.metrics.comparisons + this.metrics.swaps + this.metrics.writes;
this.onOperation(total);
}
updateMetricsDisplay() {
if (!this.metricsEl) return;
const m = this.metrics;
this.metricsEl.innerHTML = `
<span class="metric"><strong>${m.comparisons}</strong> comparisons</span>
<span class="metric"><strong>${m.swaps}</strong> swaps</span>
<span class="metric"><strong>${m.writes}</strong> writes</span>
<span class="metric"><strong>${m.elapsedMs}</strong> ms</span>
`;
}
tickElapsed() {
if (this.metrics.startTime) {
this.metrics.elapsedMs = Math.round(performance.now() - this.metrics.startTime);
this.updateMetricsDisplay();
}
}
async waitStep() {
if (this.stopped) throw new Error("STOPPED");
if (this.silent) {
return;
}
if (this.stepMode) {
await new Promise((resolve) => {
this.stepResolver = resolve;
});
if (this.stopped) throw new Error("STOPPED");
return;
}
while (this.paused) {
await new Promise((r) => setTimeout(r, 50));
if (this.stopped) throw new Error("STOPPED");
}
const delay = 202 - this.speedSlider.value * 2;
await new Promise((r) => setTimeout(r, delay));
this.tickElapsed();
}
resolveStep() {
if (this.stepResolver) {
const resolve = this.stepResolver;
this.stepResolver = null;
resolve();
}
}
async compare(i, j) {
this.metrics.comparisons++;
this.trackAccess(i, j);
if (!this.silent) {
this.bars[i]?.classList.add("compare");
this.bars[j]?.classList.add("compare");
}
this.audio?.compare();
this.updateMetricsDisplay();
this.narrate(`Now comparing indices ${i} and ${j} (values ${this.array[i]} and ${this.array[j]}).`);
this.recordOperation();
this.notifyVisualUpdate();
await this.waitStep();
}
clearCompare(i, j) {
this.bars[i]?.classList.remove("compare");
this.bars[j]?.classList.remove("compare");
}
async swap(i, j) {
this.metrics.swaps++;
this.metrics.writes += 2;
this.trackAccess(i, j);
[this.array[i], this.array[j]] = [this.array[j], this.array[i]];
if (!this.silent) {
this.bars[i].style.height = `${this.array[i]}%`;
this.bars[j].style.height = `${this.array[j]}%`;
this.bars[i].classList.add("swap");
this.bars[j].classList.add("swap");
}
this.audio?.swap();
this.updateMetricsDisplay();
this.narrate(`Swapping indices ${i} and ${j}.`);
this.recordOperation();
this.notifyVisualUpdate();
await this.waitStep();
this.bars[i]?.classList.remove("swap");
this.bars[j]?.classList.remove("swap");
}
async write(i, value) {
this.metrics.writes++;
this.trackAccess(i);
this.array[i] = value;
if (!this.silent) {
this.bars[i].style.height = `${value}%`;
this.bars[i].classList.add("write");
}
this.audio?.write();
this.updateMetricsDisplay();
this.narrate(`Writing value ${value} to index ${i}.`);
this.recordOperation();
this.notifyVisualUpdate();
await this.waitStep();
this.bars[i]?.classList.remove("write");
}
markSorted(i) {
this.bars[i]?.classList.add("sorted");
}
async markPivot(i) {
this.trackAccess(i);
this.bars[i]?.classList.add("pivot");
this.narrate(`Pivot selected at index ${i} (value ${this.array[i]}).`);
this.notifyVisualUpdate();
await this.waitStep();
}
clearPivot(i) {
this.bars[i]?.classList.remove("pivot");
}
async run(algorithm) {
this.isRunning = true;
this.stopped = false;
this.paused = false;
this.metrics.start();
this.clearStateClasses();
const runners = {
bubble: () => this.bubbleSort(),
selection: () => this.selectionSort(),
insertion: () => this.insertionSort(),
merge: () => this.mergeSort(),
quick: () => this.quickSort(),
heap: () => this.heapSort(),
shell: () => this.shellSort(),
radix: () => this.radixSort(),
counting: () => this.countingSort(),
cocktail: () => this.cocktailShakerSort(),
};
try {
await runners[algorithm]();
if (!this.silent) {
this.bars.forEach((bar) => bar.classList.add("sorted"));
}
this.narrate("Sorting complete — all elements are in order.");
} catch (err) {
if (err.message !== "STOPPED") throw err;
} finally {
this.metrics.finish();
this.updateMetricsDisplay();
this.isRunning = false;
}
}
async bubbleSort() {
const n = this.array.length;
for (let i = 0; i < n - 1; i++) {
for (let j = 0; j < n - i - 1; j++) {
await this.compare(j, j + 1);
if (this.array[j] > this.array[j + 1]) {
await this.swap(j, j + 1);
}
this.clearCompare(j, j + 1);
}
this.markSorted(n - i - 1);
}
this.markSorted(0);
}
async selectionSort() {
const n = this.array.length;
for (let i = 0; i < n - 1; i++) {
let minIdx = i;
if (!this.silent) this.bars[minIdx].classList.add("compare");
for (let j = i + 1; j < n; j++) {
await this.compare(j, minIdx);
if (this.array[j] < this.array[minIdx]) {
this.bars[minIdx]?.classList.remove("compare");
minIdx = j;
if (!this.silent) this.bars[minIdx].classList.add("compare");
} else {
this.bars[j]?.classList.remove("compare");
}
}
if (minIdx !== i) await this.swap(i, minIdx);
this.bars[minIdx]?.classList.remove("compare");
this.markSorted(i);
}
this.markSorted(n - 1);
}
async insertionSort() {
const n = this.array.length;
this.markSorted(0);
for (let i = 1; i < n; i++) {
let j = i;
if (!this.silent) this.bars[i].classList.add("compare");
while (j > 0) {
await this.compare(j - 1, j);
if (this.array[j - 1] > this.array[j]) {
await this.swap(j - 1, j);
j--;
} else {
this.clearCompare(j - 1, j);
break;
}
this.clearCompare(j - 1, j);
}
this.bars[i]?.classList.remove("compare");
for (let k = 0; k <= i; k++) this.markSorted(k);
}
}
async mergeSort() {
const aux = [...this.array];
await this.mergeSortRange(0, this.array.length - 1, aux);
}
async mergeSortRange(low, high, aux) {
if (low >= high) return;
const mid = Math.floor((low + high) / 2);
this.narrate(`Merge sort: dividing range [${low}…${high}] at midpoint ${mid}.`);
await this.mergeSortRange(low, mid, aux);
await this.mergeSortRange(mid + 1, high, aux);
await this.merge(low, mid, high, aux);
}
async merge(low, mid, high, aux) {
this.narrate(`Merging sorted halves [${low}…${mid}] and [${mid + 1}…${high}].`);
for (let k = low; k <= high; k++) {
aux[k] = this.array[k];
}
let i = low;
let j = mid + 1;
let k = low;
while (i <= mid && j <= high) {
await this.compare(i, j);
if (aux[i] <= aux[j]) {
await this.write(k, aux[i]);
i++;
} else {
await this.write(k, aux[j]);
j++;
}
this.clearCompare(i, j);
k++;
}
while (i <= mid) {
await this.write(k, aux[i]);
i++;
k++;
}
while (j <= high) {
await this.write(k, aux[j]);
j++;
k++;
}
}
async quickSort(low = 0, high = this.array.length - 1) {
if (low < high) {
const pivotIdx = await this.partition(low, high);
await this.quickSort(low, pivotIdx - 1);
await this.quickSort(pivotIdx + 1, high);
}
}
async partition(low, high) {
await this.markPivot(high);
const pivotValue = this.array[high];
let i = low - 1;
for (let j = low; j < high; j++) {
await this.compare(j, high);
if (this.array[j] < pivotValue) {
i++;
if (i !== j) await this.swap(i, j);
}
this.clearCompare(j, high);
}
await this.swap(i + 1, high);
this.clearPivot(high);
this.markSorted(i + 1);
return i + 1;
}
async heapSort() {
const n = this.array.length;
for (let i = Math.floor(n / 2) - 1; i >= 0; i--) {
await this.heapify(n, i);
}