-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
671 lines (609 loc) · 19.1 KB
/
app.js
File metadata and controls
671 lines (609 loc) · 19.1 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
/**
* Quick start: open index.html in a modern browser. Controls:
* - Space to start/pause, R to reset.
* - Use toggles for numbers/audio; speed is ms per step.
* Architecture: action generators per sort, bar renderer, playback engine with pause/step.
*/
const $ = (id) => document.getElementById(id);
const barsContainer = $('bars');
const algorithmSelect = $('algorithmSelect');
const sizeSlider = $('sizeSlider');
const speedSlider = $('speedSlider');
const presetSelect = $('presetSelect');
const sizeValue = $('sizeValue');
const speedValue = $('speedValue');
const generateBtn = $('generateBtn');
const startBtn = $('startBtn');
const pauseBtn = $('pauseBtn');
const stepBtn = $('stepBtn');
const resetBtn = $('resetBtn');
const numbersToggle = $('numbersToggle');
const audioToggle = $('audioToggle');
const togglePanelBtn = $('togglePanel');
const controlPanel = $('controlPanel');
const compareCountEl = $('compareCount');
const swapCountEl = $('swapCount');
const timeElapsedEl = $('timeElapsed');
const algoDescriptionEl = $('algoDescription');
const stabilityTag = $('stabilityTag');
const bestCaseEl = $('bestCase');
const avgCaseEl = $('avgCase');
const worstCaseEl = $('worstCase');
const infoBtn = $('infoBtn');
const infoModal = $('infoModal');
const infoTitle = $('infoTitle');
const infoBody = $('infoBody');
const infoClose = $('infoClose');
const algorithmInfo = {
bubble: {
name: 'Bubble Sort',
stable: true,
best: 'O(n)',
avg: 'O(n²)',
worst: 'O(n²)',
desc: 'Compares adjacent pairs and swaps them if out of order. Repeats until the array is sorted. Easy to grasp but inefficient.',
details: 'Bubble sort repeatedly scans the array, comparing adjacent elements and swapping when they are out of order. After each pass the largest element bubbles to the end. It is stable, simple to implement, but scales poorly on large inputs.'
},
selection: {
name: 'Selection Sort',
stable: false,
best: 'O(n²)',
avg: 'O(n²)',
worst: 'O(n²)',
desc: 'Selects the minimum in the unsorted part and moves it into place. Fewer passes but still quadratic.',
details: 'Selection sort splits the array into a sorted and an unsorted part. Each iteration finds the minimum in the unsorted zone and moves it to the front. It always does the same number of comparisons, is not stable, and remains O(n²).'
},
insertion: {
name: 'Insertion Sort',
stable: true,
best: 'O(n)',
avg: 'O(n²)',
worst: 'O(n²)',
desc: 'Inserts each element into the already sorted section by shifting larger ones. Great for small or nearly sorted arrays.',
details: 'Insertion sort treats the left side as sorted and inserts each new element into its correct position by shifting larger ones. It is stable and fast on small or nearly sorted input, but degrades to O(n²) on large random data.'
},
merge: {
name: 'Merge Sort',
stable: true,
best: 'O(n log n)',
avg: 'O(n log n)',
worst: 'O(n log n)',
desc: 'Recursively splits in halves, sorts, and merges while keeping order. Stable and guaranteed O(n log n), uses extra memory.',
details: 'Merge sort splits the array in half down to single-element subarrays, then merges while preserving order. It guarantees O(n log n) and is stable, but needs extra space for the auxiliary array.'
},
quick: {
name: 'Quick Sort',
stable: false,
best: 'O(n log n)',
avg: 'O(n log n)',
worst: 'O(n²)',
desc: 'Picks a pivot, partitions into smaller/greater, then recurses. Typically fastest in practice, but bad pivots degrade it.',
details: 'Quick sort chooses a pivot, partitions the array into elements smaller and greater than the pivot, then recursively sorts both parts. Usually very fast thanks to locality of reference, but a bad pivot leads to O(n²). It is not stable.'
},
heap: {
name: 'Heap Sort',
stable: false,
best: 'O(n log n)',
avg: 'O(n log n)',
worst: 'O(n log n)',
desc: 'Builds a max-heap and moves the maximum to the end iteratively. Log-linear, in-place, not stable.',
details: 'Heap sort builds a max-heap and repeatedly extracts the maximum by swapping it with the last position and shrinking the heap. It offers O(n log n) even in the worst case and is in-place, but not stable and with a larger constant than quick sort.'
}
};
const state = {
baseArray: [],
workingArray: [],
actions: [],
algorithm: 'bubble',
size: 50,
speed: 40,
preset: 'random',
showNumbers: true,
playAudio: false,
playing: false,
paused: false,
actionIndex: 0,
comparisons: 0,
swaps: 0,
elapsedAccum: 0,
startTimestamp: 0,
timerRAF: null,
playTimeout: null,
maxValue: 100
};
let audioCtx = null;
const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
function init() {
sizeValue.textContent = state.size;
speedValue.textContent = state.speed;
attachEvents();
updateAlgoInfo();
generateAndRender();
}
function attachEvents() {
algorithmSelect.addEventListener('change', (e) => {
state.algorithm = e.target.value;
updateAlgoInfo();
});
sizeSlider.addEventListener('input', (e) => {
state.size = Number(e.target.value);
sizeValue.textContent = state.size;
generateAndRender();
});
speedSlider.addEventListener('input', (e) => {
state.speed = Number(e.target.value);
speedValue.textContent = state.speed;
});
presetSelect.addEventListener('change', (e) => {
state.preset = e.target.value;
generateAndRender();
});
generateBtn.addEventListener('click', generateAndRender);
startBtn.addEventListener('click', startPlayback);
pauseBtn.addEventListener('click', togglePause);
stepBtn.addEventListener('click', stepOnce);
resetBtn.addEventListener('click', resetVisualizer);
numbersToggle.addEventListener('change', (e) => {
state.showNumbers = e.target.checked;
updateNumbersVisibility();
});
audioToggle.addEventListener('change', (e) => {
state.playAudio = e.target.checked;
});
togglePanelBtn.addEventListener('click', () => {
controlPanel.classList.toggle('collapsed');
const expanded = !controlPanel.classList.contains('collapsed');
togglePanelBtn.setAttribute('aria-expanded', expanded);
});
infoBtn.addEventListener('click', () => openInfoModal());
infoClose.addEventListener('click', () => closeInfoModal());
infoModal.addEventListener('click', (e) => {
if (e.target === infoModal) closeInfoModal();
});
document.addEventListener('keydown', (e) => {
if (e.code === 'Space') {
e.preventDefault();
state.playing && !state.paused ? togglePause() : startPlayback();
}
if (e.code === 'KeyR') {
resetVisualizer();
}
if (e.code === 'Escape') {
closeInfoModal();
}
});
}
function generateArray(preset, size) {
const arr = [];
if (preset === 'reversed') {
for (let i = size; i >= 1; i -= 1) arr.push(i);
} else {
for (let i = 1; i <= size; i += 1) {
const value = Math.floor(Math.random() * (size + 20)) + 5;
arr.push(value);
}
if (preset === 'nearly') {
arr.sort((a, b) => a - b);
const swaps = Math.max(1, Math.floor(size * 0.1));
for (let i = 0; i < swaps; i += 1) {
const a = Math.floor(Math.random() * size);
const b = Math.floor(Math.random() * size);
[arr[a], arr[b]] = [arr[b], arr[a]];
}
}
}
return arr;
}
function generateAndRender() {
const arr = generateArray(state.preset, state.size);
setArray(arr);
stopPlayback();
resetStats();
}
function setArray(arr) {
state.baseArray = [...arr];
state.workingArray = [...arr];
state.maxValue = Math.max(...arr);
renderBars(arr);
}
function renderBars(values) {
barsContainer.innerHTML = '';
const maxVal = Math.max(...values);
values.forEach((value) => {
const bar = document.createElement('div');
bar.className = 'bar';
const height = (value / maxVal) * 100;
bar.style.height = `${height}%`;
bar.setAttribute('role', 'img');
bar.setAttribute('aria-label', `Valore ${value}`);
const label = document.createElement('small');
label.textContent = value;
bar.appendChild(label);
barsContainer.appendChild(bar);
});
updateNumbersVisibility();
}
function updateNumbersVisibility() {
barsContainer.querySelectorAll('.bar small').forEach((el) => {
el.style.display = state.showNumbers ? 'block' : 'none';
});
}
function clearTransientClasses() {
barsContainer.querySelectorAll('.bar').forEach((bar) => {
bar.classList.remove('compare', 'swap', 'pivot', 'merge-write');
});
}
function setBarHeight(index, value) {
const bar = barsContainer.children[index];
if (!bar) return;
const height = (value / state.maxValue) * 100;
bar.style.height = `${height}%`;
const label = bar.querySelector('small');
if (label) label.textContent = value;
}
function applyAction(action) {
clearTransientClasses();
switch (action.type) {
case 'compare': {
highlightBars([action.i, action.j], 'compare');
state.comparisons += 1;
tickSound();
break;
}
case 'swap': {
const { i, j } = action;
[state.workingArray[i], state.workingArray[j]] = [state.workingArray[j], state.workingArray[i]];
setBarHeight(i, state.workingArray[i]);
setBarHeight(j, state.workingArray[j]);
highlightBars([i, j], 'swap');
state.swaps += 1;
tickSound();
break;
}
case 'set': {
const { i, value } = action;
state.workingArray[i] = value;
setBarHeight(i, value);
highlightBars([i], 'merge-write');
tickSound();
break;
}
case 'markSorted': {
action.indices.forEach((idx) => {
const bar = barsContainer.children[idx];
if (bar) bar.classList.add('sorted');
});
break;
}
case 'pivot': {
highlightBars([action.index], 'pivot');
break;
}
default:
break;
}
updateStats();
}
function highlightBars(indices, className) {
indices.forEach((idx) => {
const bar = barsContainer.children[idx];
if (bar) bar.classList.add(className);
});
}
function updateStats() {
compareCountEl.textContent = state.comparisons;
swapCountEl.textContent = state.swaps;
}
function updateTimer() {
if (!state.playing || state.paused) return;
const now = performance.now();
const elapsed = state.elapsedAccum + (now - state.startTimestamp);
timeElapsedEl.textContent = `${Math.floor(elapsed)} ms`;
state.timerRAF = requestAnimationFrame(updateTimer);
}
function startPlayback() {
if (state.playing && !state.paused) return;
if (state.actionIndex === 0 || state.actionIndex >= state.actions.length) {
buildActions();
resetStats();
state.workingArray = [...state.baseArray];
renderBars(state.workingArray);
}
pauseBtn.textContent = 'Pause';
state.playing = true;
state.paused = false;
state.startTimestamp = performance.now();
state.timerRAF = requestAnimationFrame(updateTimer);
runLoop();
}
function togglePause() {
if (!state.playing) {
startPlayback();
pauseBtn.textContent = 'Pause';
return;
}
state.paused = !state.paused;
if (state.paused) {
state.elapsedAccum += performance.now() - state.startTimestamp;
pauseBtn.textContent = 'Resume';
} else {
state.startTimestamp = performance.now();
state.timerRAF = requestAnimationFrame(updateTimer);
runLoop();
pauseBtn.textContent = 'Pause';
}
}
function stopPlayback() {
state.playing = false;
state.paused = false;
clearTimeout(state.playTimeout);
if (state.timerRAF) cancelAnimationFrame(state.timerRAF);
}
function resetStats() {
state.comparisons = 0;
state.swaps = 0;
state.elapsedAccum = 0;
state.startTimestamp = performance.now();
timeElapsedEl.textContent = '0 ms';
updateStats();
}
function resetVisualizer() {
stopPlayback();
state.actionIndex = 0;
state.actions = [];
state.workingArray = [...state.baseArray];
renderBars(state.workingArray);
barsContainer.querySelectorAll('.bar').forEach((bar) => {
bar.classList.remove('sorted', 'compare', 'swap', 'pivot', 'merge-write');
});
resetStats();
pauseBtn.textContent = 'Pause';
}
function runLoop() {
if (!state.playing || state.paused) return;
if (state.actionIndex >= state.actions.length) {
state.playing = false;
state.elapsedAccum += performance.now() - state.startTimestamp;
timeElapsedEl.textContent = `${Math.floor(state.elapsedAccum)} ms`;
pauseBtn.textContent = 'Pause';
return;
}
stepOnce(false);
state.playTimeout = setTimeout(runLoop, state.speed);
}
function stepOnce(manual = true) {
if (manual && state.actions.length === 0) {
buildActions();
resetStats();
state.workingArray = [...state.baseArray];
renderBars(state.workingArray);
}
if (state.actionIndex >= state.actions.length) return;
const action = state.actions[state.actionIndex];
applyAction(action);
state.actionIndex += 1;
}
function buildActions() {
const arrCopy = [...state.baseArray];
let actions = [];
switch (state.algorithm) {
case 'bubble':
actions = bubbleSortActions(arrCopy);
break;
case 'selection':
actions = selectionSortActions(arrCopy);
break;
case 'insertion':
actions = insertionSortActions(arrCopy);
break;
case 'merge':
actions = mergeSortActions(arrCopy);
break;
case 'quick':
actions = quickSortActions(arrCopy);
break;
case 'heap':
actions = heapSortActions(arrCopy);
break;
default:
actions = bubbleSortActions(arrCopy);
}
actions.push({ type: 'markSorted', indices: [...Array(arrCopy.length).keys()] });
state.actions = actions;
state.actionIndex = 0;
}
function bubbleSortActions(arr) {
const actions = [];
const n = arr.length;
for (let i = 0; i < n - 1; i += 1) {
for (let j = 0; j < n - i - 1; j += 1) {
actions.push({ type: 'compare', i: j, j: j + 1 });
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
actions.push({ type: 'swap', i: j, j: j + 1 });
}
}
actions.push({ type: 'markSorted', indices: [n - i - 1] });
}
actions.push({ type: 'markSorted', indices: [0] });
return actions;
}
function selectionSortActions(arr) {
const actions = [];
const n = arr.length;
for (let i = 0; i < n; i += 1) {
let min = i;
for (let j = i + 1; j < n; j += 1) {
actions.push({ type: 'compare', i: min, j });
if (arr[j] < arr[min]) min = j;
}
if (min !== i) {
[arr[i], arr[min]] = [arr[min], arr[i]];
actions.push({ type: 'swap', i, j: min });
}
actions.push({ type: 'markSorted', indices: [i] });
}
return actions;
}
function insertionSortActions(arr) {
const actions = [];
for (let i = 1; i < arr.length; i += 1) {
let j = i;
while (j > 0) {
actions.push({ type: 'compare', i: j - 1, j });
if (arr[j - 1] > arr[j]) {
[arr[j - 1], arr[j]] = [arr[j], arr[j - 1]];
actions.push({ type: 'swap', i: j - 1, j });
} else {
break;
}
j -= 1;
}
}
actions.push({ type: 'markSorted', indices: [...Array(arr.length).keys()] });
return actions;
}
function mergeSortActions(arr) {
const actions = [];
const aux = [...arr];
function merge(left, mid, right) {
let i = left;
let j = mid + 1;
let k = left;
while (i <= mid && j <= right) {
actions.push({ type: 'compare', i, j });
if (aux[i] <= aux[j]) {
arr[k] = aux[i];
actions.push({ type: 'set', i: k, value: aux[i] });
i += 1;
} else {
arr[k] = aux[j];
actions.push({ type: 'set', i: k, value: aux[j] });
j += 1;
}
k += 1;
}
while (i <= mid) {
arr[k] = aux[i];
actions.push({ type: 'set', i: k, value: aux[i] });
i += 1;
k += 1;
}
while (j <= right) {
arr[k] = aux[j];
actions.push({ type: 'set', i: k, value: aux[j] });
j += 1;
k += 1;
}
for (let t = left; t <= right; t += 1) aux[t] = arr[t];
}
function divide(left, right) {
if (left >= right) return;
const mid = Math.floor((left + right) / 2);
divide(left, mid);
divide(mid + 1, right);
merge(left, mid, right);
}
divide(0, arr.length - 1);
return actions;
}
function quickSortActions(arr) {
const actions = [];
function partition(low, high) {
const pivotVal = arr[high];
actions.push({ type: 'pivot', index: high });
let i = low;
for (let j = low; j < high; j += 1) {
actions.push({ type: 'compare', i: j, j: high });
if (arr[j] < pivotVal) {
[arr[i], arr[j]] = [arr[j], arr[i]];
actions.push({ type: 'swap', i, j });
i += 1;
}
}
[arr[i], arr[high]] = [arr[high], arr[i]];
actions.push({ type: 'swap', i, j: high });
actions.push({ type: 'markSorted', indices: [i] });
return i;
}
function quick(low, high) {
if (low >= high) {
if (low === high) actions.push({ type: 'markSorted', indices: [low] });
return;
}
const pivotIndex = partition(low, high);
quick(low, pivotIndex - 1);
quick(pivotIndex + 1, high);
}
quick(0, arr.length - 1);
return actions;
}
function heapSortActions(arr) {
const actions = [];
const n = arr.length;
function heapify(length, root) {
let largest = root;
const left = 2 * root + 1;
const right = 2 * root + 2;
if (left < length) {
actions.push({ type: 'compare', i: left, j: largest });
if (arr[left] > arr[largest]) largest = left;
}
if (right < length) {
actions.push({ type: 'compare', i: right, j: largest });
if (arr[right] > arr[largest]) largest = right;
}
if (largest !== root) {
[arr[root], arr[largest]] = [arr[largest], arr[root]];
actions.push({ type: 'swap', i: root, j: largest });
heapify(length, largest);
}
}
for (let i = Math.floor(n / 2) - 1; i >= 0; i -= 1) heapify(n, i);
for (let end = n - 1; end > 0; end -= 1) {
[arr[0], arr[end]] = [arr[end], arr[0]];
actions.push({ type: 'swap', i: 0, j: end });
actions.push({ type: 'markSorted', indices: [end] });
heapify(end, 0);
}
actions.push({ type: 'markSorted', indices: [0] });
return actions;
}
function updateAlgoInfo() {
const meta = algorithmInfo[state.algorithm];
algoDescriptionEl.textContent = meta.desc;
stabilityTag.textContent = meta.stable ? 'Stable' : 'Not stable';
bestCaseEl.textContent = meta.best;
avgCaseEl.textContent = meta.avg;
worstCaseEl.textContent = meta.worst;
setInfoModalContent(meta);
}
function tickSound() {
if (!state.playAudio) return;
if (!audioCtx) audioCtx = new AudioContext();
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
osc.type = 'sine';
osc.frequency.value = 420;
gain.gain.value = 0.05;
osc.connect(gain);
gain.connect(audioCtx.destination);
osc.start();
osc.stop(audioCtx.currentTime + 0.08);
}
function setInfoModalContent(meta) {
infoTitle.textContent = meta.name;
infoBody.textContent = meta.details;
}
function openInfoModal() {
const meta = algorithmInfo[state.algorithm];
setInfoModalContent(meta);
infoModal.classList.add('open');
infoModal.setAttribute('aria-hidden', 'false');
infoClose.focus();
}
function closeInfoModal() {
infoModal.classList.remove('open');
infoModal.setAttribute('aria-hidden', 'true');
}
init();