Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
913 lines (782 loc) · 36.7 KB
/
Copy pathindex.html
File metadata and controls
913 lines (782 loc) · 36.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sorting Algorithm Visualizer</title>
<!-- Load Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<style>
/* Custom styles for the bars */
.bar {
width: 1rem; /* Slightly reduced width to fit 6 algorithms */
margin: 0 1px;
background-color: #3b82f6; /* Blue-500 default */
transition: all 0.1s ease-in-out; /* Faster transitions for 6 algorithms */
border-radius: 2px 2px 0 0;
display: flex;
align-items: flex-end;
justify-content: center;
font-size: 0.6rem; /* Smaller font for values */
color: white;
padding-bottom: 2px;
position: relative;
min-height: 5px; /* Ensure tiny bars are visible */
}
/* Color classes for visualization */
.bar-default { background-color: #3b82f6; } /* Blue */
.bar-compare { background-color: #f59e0b; } /* Amber/Yellow */
.bar-swap { background-color: #ef4444; } /* Red */
.bar-sorted { background-color: #10b981; } /* Emerald/Green */
.bar-pivot { background-color: #8b5cf6; } /* Violet/Purple */
/* Animation container styles */
.visualizer {
height: 180px; /* Reduced height to fit 6 in view */
display: flex;
align-items: flex-end;
justify-content: center;
padding: 0.5rem 0.25rem;
background-color: #f9fafb;
border-radius: 0.5rem;
overflow: hidden;
box-shadow: inset 0 2px 4px 0 rgba(0, 0, 0, 0.06);
}
.algorithm-title {
font-weight: 700;
color: #1f2937;
/* Reset default margins/borders for title when wrapped in flex */
margin: 0;
border-bottom: none;
padding-bottom: 0;
}
.algorithm-description {
background-color: #1f2937;
color: #d1d5db;
padding: 0.75rem;
border-radius: 0.5rem;
font-family: monospace;
font-size: 0.7rem;
white-space: pre-wrap;
overflow-x: auto;
max-height: 200px;
}
</style>
</head>
<body class="bg-gray-50 min-h-screen font-sans p-6 md:p-10">
<div class="max-w-7xl mx-auto">
<h1 class="text-3xl font-extrabold text-gray-800 mb-2">Sorting Algorithm Visualizer (6 Algorithms)</h1>
<p class="text-gray-600 mb-6">Observe the different approaches of six common sorting algorithms simultaneously, or run them individually.</p>
<div class="flex flex-col sm:flex-row gap-4 mb-8">
<button id="startVisualization"
class="w-full sm:w-auto bg-violet-600 hover:bg-violet-700 text-white font-semibold py-3 px-6 rounded-lg shadow-md transition duration-200 disabled:opacity-50 disabled:cursor-not-allowed">
Start All Visualizations
</button>
<button id="resetArray"
class="w-full sm:w-auto bg-gray-500 hover:bg-gray-600 text-white font-semibold py-3 px-6 rounded-lg shadow-md transition duration-200 disabled:opacity-50 disabled:cursor-not-allowed">
Reset Array
</button>
<button id="pauseVisualization"
class="w-full sm:w-auto bg-yellow-500 hover:bg-yellow-600 text-white font-semibold py-3 px-6 rounded-lg shadow-md transition duration-200 disabled:opacity-50 disabled:cursor-not-allowed">
Pause
</button>
<select id="speedSelector" class="w-full sm:w-auto py-3 px-4 rounded-lg border border-gray-300 shadow-sm focus:ring-violet-500 focus:border-violet-500">
<option value="400">Slow (400ms)</option>
<option value="150" selected>Medium (150ms)</option>
<option value="50">Fast (50ms)</option>
<option value="10">Turbo (10ms)</option>
</select>
</div>
<!-- Visualization Containers (3 columns, 2 rows for 6 algorithms) -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
<!-- Row 1: Bubble Sort -->
<div class="bg-white p-4 rounded-xl shadow-lg">
<div class="flex justify-between items-center mb-2 border-b-2 border-gray-200 pb-1">
<h2 class="algorithm-title">Bubble Sort</h2>
<button id="runBubbleSort" class="bg-green-600 hover:bg-green-700 text-white text-xs font-semibold py-1 px-3 rounded-md shadow transition duration-150 disabled:opacity-50 disabled:cursor-not-allowed">Run</button>
</div>
<div id="bubbleSortVisualizer" class="visualizer"></div>
<pre class="algorithm-description">
for i from 0 to n-1:
for j from 0 to n-i-2:
if array[j] > array[j+1]:
swap(array[j], array[j+1])
</pre>
</div>
<!-- Row 1: Insertion Sort -->
<div class="bg-white p-4 rounded-xl shadow-lg">
<div class="flex justify-between items-center mb-2 border-b-2 border-gray-200 pb-1">
<h2 class="algorithm-title">Insertion Sort</h2>
<button id="runInsertionSort" class="bg-green-600 hover:bg-green-700 text-white text-xs font-semibold py-1 px-3 rounded-md shadow transition duration-150 disabled:opacity-50 disabled:cursor-not-allowed">Run</button>
</div>
<div id="insertionSortVisualizer" class="visualizer"></div>
<pre class="algorithm-description">
for i from 1 to n-1:
key = array[i]
j = i - 1
// Move key backward by swapping until sorted position is found
while j >= 0 AND array[j] > array[j+1]:
swap(array[j], array[j+1])
j = j - 1
</pre>
</div>
<!-- Row 1: Quick Sort -->
<div class="bg-white p-4 rounded-xl shadow-lg">
<div class="flex justify-between items-center mb-2 border-b-2 border-gray-200 pb-1">
<h2 class="algorithm-title">Quick Sort</h2>
<button id="runQuickSort" class="bg-green-600 hover:bg-green-700 text-white text-xs font-semibold py-1 px-3 rounded-md shadow transition duration-150 disabled:opacity-50 disabled:cursor-not-allowed">Run</button>
</div>
<div id="quickSortVisualizer" class="visualizer"></div>
<pre class="algorithm-description">
function quick_sort(low, high):
if low < high:
pivot_index = partition(low, high)
quick_sort(low, pivot_index - 1)
quick_sort(pivot_index + 1, high)
function partition(low, high):
pivot = array[high]
i = low - 1
for j from low to high - 1:
if array[j] < pivot:
i++
swap(array[i], array[j])
swap(array[i + 1], array[high])
return i + 1
</pre>
</div>
<!-- Row 2: Selection Sort (NEW) -->
<div class="bg-white p-4 rounded-xl shadow-lg">
<div class="flex justify-between items-center mb-2 border-b-2 border-gray-200 pb-1">
<h2 class="algorithm-title">Selection Sort</h2>
<button id="runSelectionSort" class="bg-green-600 hover:bg-green-700 text-white text-xs font-semibold py-1 px-3 rounded-md shadow transition duration-150 disabled:opacity-50 disabled:cursor-not-allowed">Run</button>
</div>
<div id="selectionSortVisualizer" class="visualizer"></div>
<pre class="algorithm-description">
for i from 0 to n-2:
min_idx = i
for j from i+1 to n-1:
if array[j] < array[min_idx]:
min_idx = j
swap(array[i], array[min_idx])
</pre>
</div>
<!-- Row 2: Heap Sort (NEW) -->
<div class="bg-white p-4 rounded-xl shadow-lg">
<div class="flex justify-between items-center mb-2 border-b-2 border-gray-200 pb-1">
<h2 class="algorithm-title">Heap Sort</h2>
<button id="runHeapSort" class="bg-green-600 hover:bg-green-700 text-white text-xs font-semibold py-1 px-3 rounded-md shadow transition duration-150 disabled:opacity-50 disabled:cursor-not-allowed">Run</button>
</div>
<div id="heapSortVisualizer" class="visualizer"></div>
<pre class="algorithm-description">
function build_max_heap():
for i from n/2 - 1 down to 0:
heapify(n, i)
function heapify(n, i):
largest = i
l = 2*i + 1
r = 2*i + 2
if l < n AND array[l] > array[largest]:
largest = l
if r < n AND array[r] > array[largest]:
largest = r
if largest != i:
swap(array[i], array[largest])
heapify(n, largest)
build_max_heap()
for i from n-1 down to 1:
swap(array[0], array[i])
heapify(i, 0)
</pre>
</div>
<!-- Row 2: Merge Sort (IMPROVED VISUAL) -->
<div class="bg-white p-4 rounded-xl shadow-lg">
<div class="flex justify-between items-center mb-2 border-b-2 border-gray-200 pb-1">
<h2 class="algorithm-title">Merge Sort</h2>
<button id="runMergeSort" class="bg-green-600 hover:bg-green-700 text-white text-xs font-semibold py-1 px-3 rounded-md shadow transition duration-150 disabled:opacity-50 disabled:cursor-not-allowed">Run</button>
</div>
<div id="mergeSortVisualizer" class="visualizer"></div>
<pre class="algorithm-description">
function merge_sort(p, r):
if p < r:
q = floor((p + r) / 2)
merge_sort(p, q)
merge_sort(q + 1, r)
merge(p, q, r)
function merge(p, q, r):
// Compares and writes elements from the two sorted
// sub-arrays back into the main array sequentially.
// Visualization now shows comparisons and the sequential
// 'writing' of the sorted result back into the array.
</pre>
</div>
</div>
</div>
<script>
// --- Configuration and Global State ---
const ARRAY_SIZE = 15;
const MAX_VALUE = 90; // Max percentage height for the bars
let ANIMATION_SPEED_MS = 150;
let isRunning = false;
let isPaused = false; // NEW PAUSE STATE
// DOM Elements
const startButton = document.getElementById('startVisualization');
const resetButton = document.getElementById('resetArray');
const pauseButton = document.getElementById('pauseVisualization'); // NEW PAUSE BUTTON
const speedSelector = document.getElementById('speedSelector');
const ALGORITHMS = {
'bubbleSort': { containerId: 'bubbleSortVisualizer', actionGetter: getBubbleSortActions, runBtnId: 'runBubbleSort' },
'insertionSort': { containerId: 'insertionSortVisualizer', actionGetter: getInsertionSortActions, runBtnId: 'runInsertionSort' },
'quickSort': { containerId: 'quickSortVisualizer', actionGetter: getQuickSortActions, runBtnId: 'runQuickSort' },
'selectionSort': { containerId: 'selectionSortVisualizer', actionGetter: getSelectionSortActions, runBtnId: 'runSelectionSort' },
'heapSort': { containerId: 'heapSortVisualizer', actionGetter: getHeapSortActions, runBtnId: 'runHeapSort' },
'mergeSort': { containerId: 'mergeSortVisualizer', actionGetter: getMergeSortActions, runBtnId: 'runMergeSort' }
};
// Initial array state
let initialArray = [];
// Utility function to introduce a delay in an async function
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// NEW function to wait if the visualization is paused
const waitIfPaused = () => new Promise(resolve => {
const check = () => {
// If running AND paused, keep checking. If not running, or not paused, proceed.
if (isRunning && isPaused) {
requestAnimationFrame(check); // Use RAF for smoother checking
} else {
resolve();
}
};
check();
});
// --- Array Generation and Management ---
/**
* Generates a new array of random unique integers.
* @returns {number[]} The generated array.
*/
function generateRandomArray() {
const arr = [];
while (arr.length < ARRAY_SIZE) {
const randomVal = Math.floor(Math.random() * (MAX_VALUE - 5) + 5); // Values between 5 and MAX_VALUE
if (!arr.includes(randomVal)) {
arr.push(randomVal);
}
}
return arr;
}
/**
* Initializes the array and renders the initial bars in the specified container.
* @param {string} containerId - The ID of the container div.
* @param {number[]} array - The array data.
*/
function renderInitialArray(containerId, array) {
const container = document.getElementById(containerId);
container.innerHTML = ''; // Clear previous content
array.forEach((value, index) => {
const bar = document.createElement('div');
bar.className = 'bar bar-default';
bar.style.height = `${value}%`;
bar.style.order = index; // Used to keep the visual order corresponding to the array index
bar.setAttribute('data-value', value);
bar.setAttribute('data-index', index);
container.appendChild(bar);
});
}
// --- Visualizer Class ---
class Visualizer {
/**
* @param {string} containerId - The ID of the container element.
*/
constructor(containerId) {
this.container = document.getElementById(containerId);
this.isAnimating = false;
}
getBar(index) {
// Find the bar element based on its data-index attribute (the logical array index)
return this.container.querySelector(`[data-index="${index}"]`);
}
getBarByValue(value) {
// Find the bar element based on its data-value attribute, without checking its sorted status
// We rely on the uniqueness of values.
return this.container.querySelector(`[data-value="${value}"]`);
}
/**
* Executes a single recorded action with animation.
* @param {object} action - The action object from the sorting logic.
*/
async executeAction(action) {
this.isAnimating = true;
const bars = Array.from(this.container.children);
const clearColors = () => {
bars.forEach(bar => {
if (!bar.classList.contains('bar-sorted')) {
bar.className = 'bar bar-default';
}
});
};
// Clear temporary comparison/swap colors from previous step
clearColors();
switch (action.type) {
case 'compare':
// Highlight elements being compared (Yellow)
action.indices.forEach(i => {
const bar = this.getBar(i);
if (bar && !bar.classList.contains('bar-sorted')) {
bar.className = 'bar bar-compare';
}
});
break;
case 'swap':
// Highlight elements being swapped (Red)
const [i, j] = action.indices;
const barI = this.getBar(i);
const barJ = this.getBar(j);
if (barI && barJ) {
barI.className = 'bar bar-swap';
barJ.className = 'bar bar-swap';
// Actual DOM element swap to visually show the movement
const orderI = barI.style.order;
barI.style.order = barJ.style.order;
barJ.style.order = orderI;
// Swap the hidden data-index to track positions internally for future steps
barI.setAttribute('data-index', j);
barJ.setAttribute('data-index', i);
} else {
console.error(`Swap Error: One or both bars at indices [${i}, ${j}] not found. (BarI: ${!!barI}, BarJ: ${!!barJ})`);
}
break;
case 'write_value': // Used for Merge Sort (non-in-place result)
const targetIndex = action.index;
const valueToWrite = action.value;
// Find the bar element that holds this value (anywhere)
const valueBar = this.getBarByValue(valueToWrite);
// Get the bar currently occupying the target position (to steal its visual order)
const targetBar = this.getBar(targetIndex);
if (valueBar && targetBar) {
// If the bar is already at the correct visual index (e.g. overwriting itself), just mark sorted
if (valueBar === targetBar) {
valueBar.className = 'bar bar-sorted';
} else {
// We need to SWAP the valueBar into the target position
// and move the targetBar (which is garbage/placeholder now) to valueBar's old position
// so that every index 0..N-1 still maps to a DOM element.
const oldIndex = valueBar.getAttribute('data-index');
const targetOrder = targetBar.style.order;
const oldOrder = valueBar.style.order;
// Swap visual orders
valueBar.style.order = targetOrder;
targetBar.style.order = oldOrder;
// Swap logical indices
valueBar.setAttribute('data-index', targetIndex);
targetBar.setAttribute('data-index', oldIndex);
// Mark the correct one as sorted
valueBar.className = 'bar bar-sorted';
}
} else {
// Log error for debugging, but prevent crash
console.error(`Merge Sort Write Error: Value ${valueToWrite} or target index ${targetIndex} not found. ValueBar: ${!!valueBar}, TargetBar: ${!!targetBar}`);
}
break;
case 'pivot':
// Highlight the pivot element (Violet)
const pivotBar = this.getBar(action.index);
if (pivotBar) {
pivotBar.className = 'bar bar-pivot';
}
break;
case 'sorted':
// Mark the element as permanently sorted (Green)
const sortedBar = this.getBar(action.index);
if (sortedBar) {
sortedBar.className = 'bar bar-sorted';
}
break;
case 'merge_segment':
// Highlight the segment being worked on (Yellow)
action.indices.forEach(i => {
const bar = this.getBar(i);
if (bar) {
bar.className = 'bar bar-compare';
}
});
break;
}
await delay(ANIMATION_SPEED_MS);
// For actions that don't transition to 'sorted', revert colors after delay
if (action.type !== 'sorted' && action.type !== 'write_value') {
clearColors();
}
this.isAnimating = false;
}
}
// --- Sorting Logic (Generates Actions) ---
/**
* Records the steps for Bubble Sort.
*/
function getBubbleSortActions(arr) {
const array = [...arr];
const actions = [];
const n = array.length;
let swapped;
for (let i = 0; i < n - 1; i++) {
swapped = false;
for (let j = 0; j < n - 1 - i; j++) {
actions.push({ type: 'compare', indices: [j, j + 1] });
if (array[j] > array[j + 1]) {
actions.push({ type: 'swap', indices: [j, j + 1] });
[array[j], array[j + 1]] = [array[j + 1], array[j]];
swapped = true;
}
}
actions.push({ type: 'sorted', index: n - 1 - i });
if (!swapped) {
for (let k = 0; k < n - i - 1; k++) {
actions.push({ type: 'sorted', index: k });
}
break;
}
}
if (actions.slice(-1)[0]?.type !== 'sorted') {
actions.push({ type: 'sorted', index: 0 });
}
return actions;
}
/**
* Records the steps for Insertion Sort (REFACTORED to use swaps).
*/
function getInsertionSortActions(arr) {
const array = [...arr];
const actions = [];
const n = array.length;
for (let i = 1; i < n; i++) {
// Key element's current index
let keyIndex = i;
let j = i - 1;
actions.push({ type: 'pivot', index: keyIndex }); // Highlight the element being inserted
// Loop backward, swapping the key element left until it is larger than its left neighbor
while (j >= 0 && array[j] > array[keyIndex]) {
// Compare the two
actions.push({ type: 'compare', indices: [j, keyIndex] });
// Swap array[j] and array[keyIndex]
actions.push({ type: 'swap', indices: [j, keyIndex] });
[array[j], array[keyIndex]] = [array[keyIndex], array[j]];
keyIndex = j; // The key has moved one step left
j--;
}
// Mark all elements up to i as sorted
for (let k = 0; k <= i; k++) {
actions.push({ type: 'sorted', index: k });
}
}
return actions;
}
/**
* Records the steps for Quick Sort (in-place partitioning).
*/
function getQuickSortActions(arr) {
const array = [...arr];
const actions = [];
function partition(low, high) {
const pivot = array[high];
actions.push({ type: 'pivot', index: high });
let i = low - 1;
for (let j = low; j < high; j++) {
actions.push({ type: 'compare', indices: [j, high] });
if (array[j] < pivot) {
i++;
actions.push({ type: 'swap', indices: [i, j] });
[array[i], array[j]] = [array[j], array[i]];
}
}
actions.push({ type: 'swap', indices: [i + 1, high] });
[array[i + 1], array[high]] = [array[high], array[i + 1]];
actions.push({ type: 'sorted', index: i + 1 });
return i + 1;
}
function quickSort(low, high) {
if (low < high) {
const pi = partition(low, high);
quickSort(low, pi - 1);
quickSort(pi + 1, high);
} else if (low === high) {
actions.push({ type: 'sorted', index: low });
}
}
quickSort(0, array.length - 1);
return actions;
}
/**
* Records the steps for Selection Sort.
*/
function getSelectionSortActions(arr) {
const array = [...arr];
const actions = [];
const n = array.length;
for (let i = 0; i < n - 1; i++) {
let min_idx = i;
for (let j = i + 1; j < n; j++) {
// Highlight comparison between current minimum and j
actions.push({ type: 'compare', indices: [min_idx, j] });
if (array[j] < array[min_idx]) {
min_idx = j;
}
}
// Swap the found minimum element with the element at index i
if (min_idx !== i) {
actions.push({ type: 'swap', indices: [i, min_idx] });
[array[i], array[min_idx]] = [array[min_idx], array[i]];
}
// Mark element at i as sorted (it is the next smallest element)
actions.push({ type: 'sorted', index: i });
}
// Last element is automatically sorted
actions.push({ type: 'sorted', index: n - 1 });
return actions;
}
/**
* Records the steps for Heap Sort (in-place).
*/
function getHeapSortActions(arr) {
const array = [...arr];
const actions = [];
const n = array.length;
// Helper to perform and record swap
const recordSwap = (i, j) => {
actions.push({ type: 'swap', indices: [i, j] });
[array[i], array[j]] = [array[j], array[i]];
};
// To heapify a subtree rooted with node i
function heapify(n, i) {
let largest = i;
const l = 2 * i + 1;
const r = 2 * i + 2;
actions.push({ type: 'pivot', index: i });
if (l < n) actions.push({ type: 'compare', indices: [largest, l] });
if (l < n && array[l] > array[largest]) {
largest = l;
}
if (r < n) actions.push({ type: 'compare', indices: [largest, r] });
if (r < n && array[r] > array[largest]) {
largest = r;
}
if (largest !== i) {
recordSwap(i, largest);
heapify(n, largest);
}
}
// Build max heap
for (let i = Math.floor(n / 2) - 1; i >= 0; i--) {
heapify(n, i);
}
// Extract elements
for (let i = n - 1; i > 0; i--) {
recordSwap(0, i);
actions.push({ type: 'sorted', index: i });
heapify(i, 0);
}
actions.push({ type: 'sorted', index: 0 });
return actions;
}
/**
* Records the steps for Merge Sort (FIXED visualization using 'write_value').
*/
function getMergeSortActions(arr) {
const array = [...arr];
const actions = [];
function merge(p, q, r) {
// 1. Highlight the full segment being considered (Yellow/Compare color)
const fullSegment = [];
for (let k = p; k <= r; k++) { fullSegment.push(k); }
actions.push({ type: 'merge_segment', indices: fullSegment });
// Create temporary arrays
const L = array.slice(p, q + 1);
const R = array.slice(q + 1, r + 1);
let i = 0; // index for L
let j = 0; // index for R
let k = p; // index for merged array (array)
// 2. Simulate Merge comparisons and write-back
while (i < L.length && j < R.length) {
const originalIndexL = p + i;
const originalIndexR = q + 1 + j;
actions.push({ type: 'compare', indices: [originalIndexL, originalIndexR] });
let valueToCopy;
if (L[i] <= R[j]) {
valueToCopy = L[i];
i++;
} else {
valueToCopy = R[j];
j++;
}
// Record 'write' action (moves the bar with valueToCopy to index k)
actions.push({ type: 'write_value', index: k, value: valueToCopy });
array[k] = valueToCopy; // Update internal array state
k++;
}
// 3. Copy remaining elements of L[]
while (i < L.length) {
let valueToCopy = L[i];
actions.push({ type: 'write_value', index: k, value: valueToCopy });
array[k] = valueToCopy;
i++;
k++;
}
// 4. Copy remaining elements of R[]
while (j < R.length) {
let valueToCopy = R[j];
actions.push({ type: 'write_value', index: k, value: valueToCopy });
array[k] = valueToCopy;
j++;
k++;
}
}
function mergeSort(p, r) {
if (p < r) {
const q = Math.floor((p + r) / 2);
mergeSort(p, q);
mergeSort(q + 1, r);
merge(p, q, r);
} else if (p === r) {
// Base case: single element is sorted
actions.push({ type: 'sorted', index: p });
}
}
mergeSort(0, array.length - 1);
return actions;
}
// --- Main Visualization Runner Functions ---
/**
* Runs the full visualization for a single algorithm.
*/
async function runVisualization(visualizer, actions) {
let nextIndex = 0;
while (nextIndex < actions.length && isRunning) {
const action = actions[nextIndex];
// Execute the action visually
await visualizer.executeAction(action);
// PAUSE CHECK: Wait here if the user has paused the visualization
await waitIfPaused();
nextIndex++;
}
if (isRunning) {
console.log(`${visualizer.container.id} finished sorting.`);
}
}
/**
* Toggles the global pause state.
*/
function togglePause() {
if (!isRunning) return;
isPaused = !isPaused;
if (isPaused) {
pauseButton.textContent = 'Resume';
pauseButton.classList.replace('bg-yellow-500', 'bg-red-500');
} else {
pauseButton.textContent = 'Pause';
pauseButton.classList.replace('bg-red-500', 'bg-yellow-500');
}
}
/**
* Updates the disabled state of control buttons based on the mode.
* @param {string} mode - 'start_all', 'start_single', or 'stop'.
* @param {string | null} [currentContainerId=null] - The container ID if running single.
*/
function updateControlState(mode, currentContainerId = null) {
const running = mode !== 'stop';
// Start All and Reset are disabled while anything is running
startButton.disabled = running;
resetButton.disabled = running;
// Pause is enabled only while running
pauseButton.disabled = !running;
// Speed selector MUST remain ENABLED (as per user request)
speedSelector.disabled = false;
Object.values(ALGORITHMS).forEach(alg => {
const btn = document.getElementById(alg.runBtnId);
if (btn) {
if (mode === 'stop') {
btn.disabled = false; // Enable all run buttons on stop
} else if (mode === 'start_all') {
btn.disabled = true; // Disable all run buttons on start_all
} else if (mode === 'start_single') {
// Disable ONLY the currently running button, keep others ENABLED (as per user request)
btn.disabled = (alg.containerId === currentContainerId);
}
}
});
// Reset pause button state if stopping
if (mode === 'stop') {
isPaused = false;
pauseButton.textContent = 'Pause';
pauseButton.classList.replace('bg-red-500', 'bg-yellow-500');
}
}
/**
* Runs a single visualization.
*/
async function runSingleVisualization(containerId, actionGetter) {
if (isRunning) return;
isRunning = true;
updateControlState('start_single', containerId);
// Re-render the initial array for this single visualizer
renderInitialArray(containerId, initialArray);
// Generate actions and run
const actions = actionGetter(initialArray);
const visualizer = new Visualizer(containerId);
await runVisualization(visualizer, actions);
// Re-enable buttons after run
isRunning = false;
updateControlState('stop');
}
/**
* Initializes and starts all six visualizations concurrently.
*/
async function startAllVisualizations() {
if (isRunning) return;
isRunning = true;
updateControlState('start_all');
// Set up an array of promises to run them concurrently
const promises = Object.values(ALGORITHMS).map(alg => {
// Render initial array for each before running
renderInitialArray(alg.containerId, initialArray);
const actions = alg.actionGetter(initialArray);
const visualizer = new Visualizer(alg.containerId);
return runVisualization(visualizer, actions);
});
// Wait for all to finish
await Promise.all(promises);
isRunning = false;
updateControlState('stop');
}
/**
* Main function to set up the application state.
*/
function setup() {
// 1. Generate the initial random array
initialArray = generateRandomArray();
// 2. Render the initial array state in all containers
Object.values(ALGORITHMS).forEach(alg => {
renderInitialArray(alg.containerId, initialArray);
});
// 3. Set initial speed
ANIMATION_SPEED_MS = parseInt(speedSelector.value);
// 4. Attach event listeners
startButton.onclick = startAllVisualizations;
pauseButton.onclick = togglePause; // NEW PAUSE LISTENER
resetButton.onclick = () => {
if (isRunning) return;
setup(); // Re-run setup to reset array and visualization
};
speedSelector.onchange = (e) => {
ANIMATION_SPEED_MS = parseInt(e.target.value);
};
// 5. Attach individual run button listeners
Object.values(ALGORITHMS).forEach(alg => {
const btn = document.getElementById(alg.runBtnId);
if (btn) {
btn.onclick = () => runSingleVisualization(alg.containerId, alg.actionGetter);
}
});
startButton.textContent = 'Start All Visualizations';
updateControlState('stop'); // Set initial state
}
// Initialize the app on window load
window.onload = setup;
</script>
</body>
</html>