-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
514 lines (448 loc) · 17.9 KB
/
Copy pathscript.js
File metadata and controls
514 lines (448 loc) · 17.9 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
// --- DOM Elements ---
const arrayContainer = document.getElementById('arrayContainer');
const countArrayContainer = document.getElementById('countArrayContainer');
const sizeSlider = document.getElementById('arraySize');
const sizeValue = document.getElementById('sizeValue');
const speedSlider = document.getElementById('speedControl');
const speedValue = document.getElementById('speedValue');
const algoSelect = document.getElementById('algorithmSelect');
const generateBtn = document.getElementById('generateBtn');
const startBtn = document.getElementById('startBtn');
const pauseBtn = document.getElementById('pauseBtn');
const stepBtn = document.getElementById('stepBtn');
const resetBtn = document.getElementById('resetBtn');
const toggleThemeBtn = document.getElementById('toggleTheme');
const toggleSoundBtn = document.getElementById('toggleSound');
const moonIcon = document.getElementById('moon-icon');
const sunIcon = document.getElementById('sun-icon');
const soundOnIcon = document.getElementById('sound-on-icon');
const soundOffIcon = document.getElementById('sound-off-icon');
const algoTitle = document.getElementById('algoTitle');
const algoDescription = document.getElementById('algoDescription');
const timeBest = document.getElementById('timeBest');
const timeAverage = document.getElementById('timeAverage');
const timeWorst = document.getElementById('timeWorst');
const spaceWorst = document.getElementById('spaceWorst');
const comparisonsCountEl = document.getElementById('comparisonsCount');
const swapsCountEl = document.getElementById('swapsCount');
// --- Global State ---
let array = [];
let countArray = []; // For counting sort
let bars = []; // DOM elements
let countBars = []; // DOM elements for counting sort Array
let delayTime = 50;
let isSorting = false;
let isPaused = false;
let isSoundOn = true;
let currentResolvePause = null;
let abortController = null;
let comparisonsCount = 0;
let swapsCount = 0;
// Algorithm Details mapping
const ALGO_DETAILS = {
bubble: {
title: "Bubble Sort",
description: "A simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order.",
time: { best: "O(n)", avg: "O(n²)", worst: "O(n²)" },
space: "O(1)"
},
selection: {
title: "Selection Sort",
description: "An in-place comparison sorting algorithm that divides the input list into two parts: a sorted sublist of items and a sublist of the remaining unsorted items.",
time: { best: "O(n²)", avg: "O(n²)", worst: "O(n²)" },
space: "O(1)"
},
insertion: {
title: "Insertion Sort",
description: "A simple sorting algorithm that builds the final sorted array one item at a time. It is much less efficient on large lists than more advanced algorithms.",
time: { best: "O(n)", avg: "O(n²)", worst: "O(n²)" },
space: "O(1)"
},
merge: {
title: "Merge Sort",
description: "An efficient, stable, divide-and-conquer algorithm. Most implementations produce a stable sort, which means that the order of equal elements is the same in the input and output.",
time: { best: "O(n log n)", avg: "O(n log n)", worst: "O(n log n)" },
space: "O(n)"
},
quick: {
title: "Quick Sort",
description: "An efficient divide-and-conquer sorting algorithm. It works by selecting a 'pivot' element and partitioning the other elements into two sub-arrays according to whether they are less than or greater than the pivot.",
time: { best: "O(n log n)", avg: "O(n log n)", worst: "O(n²)" },
space: "O(log n)"
},
heap: {
title: "Heap Sort",
description: "A comparison-based sorting algorithm that uses a binary heap data structure. It divides its input into a sorted and an unsorted region, and iteratively shrinks the unsorted region.",
time: { best: "O(n log n)", avg: "O(n log n)", worst: "O(n log n)" },
space: "O(1)"
},
counting: {
title: "Counting Sort",
description: "An integer sorting algorithm that operates by counting the number of objects that have each distinct key value, and using arithmetic on those counts to determine each key's position.",
time: { best: "O(n + k)", avg: "O(n + k)", worst: "O(n + k)" },
space: "O(k)"
},
radix: {
title: "Radix Sort",
description: "A non-comparative sorting algorithm that avoids comparison by creating and distributing elements into buckets according to their radix.",
time: { best: "O(nk)", avg: "O(nk)", worst: "O(nk)" },
space: "O(n + k)"
}
};
// --- Audio Context for Sound Effects ---
let audioCtx = null;
function playNote(freq, type = 'sine') {
if (!isSoundOn) return;
if (!audioCtx) {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
}
const osc = audioCtx.createOscillator();
const node = audioCtx.createGain();
osc.type = type;
osc.frequency.value = freq;
osc.connect(node);
node.connect(audioCtx.destination);
osc.start();
node.gain.exponentialRampToValueAtTime(0.00001, audioCtx.currentTime + 0.1);
osc.stop(audioCtx.currentTime + 0.1);
}
// --- Array Generation & Rendering ---
function generateNewArray() {
if (isSorting) return;
const size = parseInt(sizeSlider.value);
array = [];
arrayContainer.innerHTML = '';
bars = [];
comparisonsCount = 0;
swapsCount = 0;
updateStats();
// Reset Count Array if visible
countArrayContainer.style.display = 'none';
countArrayContainer.innerHTML = '';
countBars = [];
const containerWidth = arrayContainer.clientWidth;
const padding = 2; // gap between bars
let barWidth = (containerWidth / size) - padding;
if (barWidth < 1) barWidth = 1;
for (let i = 0; i < size; i++) {
// Random value between 10 and 100 for percentage height
const val = Math.floor(Math.random() * 95) + 5;
array.push(val);
const bar = document.createElement('div');
bar.classList.add('array-bar');
bar.style.height = `${val}%`;
bar.style.width = `${barWidth}px`;
// Only show value if width is large enough
if (barWidth > 20) {
bar.classList.add('show-value');
const valSpan = document.createElement('span');
valSpan.classList.add('array-bar-value');
valSpan.innerText = val;
bar.appendChild(valSpan);
}
arrayContainer.appendChild(bar);
bars.push(bar);
}
}
// --- Animation Engine ---
function updateSpeed() {
// Speed from 1 to 100
// If speed is 1 (slowest), delay is e.g. 500ms
// If speed is 100 (fastest), delay is 1ms
const speed = parseInt(speedSlider.value);
delayTime = Math.floor(10000 / (speed * speed));
if (delayTime < 1) delayTime = 1;
let speedText = "Normal";
if (speed < 30) speedText = "Slow";
else if (speed > 80) speedText = "Fast";
speedValue.innerText = speedText;
}
const sleep = () => {
return new Promise(resolve => {
setTimeout(resolve, delayTime);
});
};
const waitForPause = async () => {
while (isPaused) {
await new Promise(resolve => {
currentResolvePause = resolve;
});
}
};
const checkAbort = () => {
if (abortController && abortController.signal.aborted) {
throw new Error('Animation Aborted');
}
};
async function executeSteps(steps) {
for (let s = 0; s < steps.length; s++) {
checkAbort();
await waitForPause();
const step = steps[s];
if (step.type === 'compare') {
const [i, j] = step.indices;
if (bars[i]) bars[i].classList.add('bar-compare');
if (bars[j]) bars[j].classList.add('bar-compare');
comparisonsCount++;
playNote(200 + (array[i] || 10) * 2);
updateStats();
await sleep();
checkAbort();
if (bars[i]) bars[i].classList.remove('bar-compare');
if (bars[j]) bars[j].classList.remove('bar-compare');
}
else if (step.type === 'swap' || step.type === 'overwrite') {
const [i, j] = step.indices; // for swap, indices to swap. for overwrite, i is index, j is new value.
if (step.type === 'swap') {
if (bars[i]) bars[i].classList.add('bar-swap');
if (bars[j]) bars[j].classList.add('bar-swap');
// Audio
playNote(400 + array[i] * 5, 'triangle');
// DOM height swap
const tempHeight = bars[i].style.height;
bars[i].style.height = bars[j].style.height;
bars[j].style.height = tempHeight;
// Value swap
if (bars[i].classList.contains('show-value')) {
const tempVal = bars[i].querySelector('.array-bar-value').innerText;
bars[i].querySelector('.array-bar-value').innerText = bars[j].querySelector('.array-bar-value').innerText;
bars[j].querySelector('.array-bar-value').innerText = tempVal;
}
} else { // overwrite
if (bars[i]) {
bars[i].classList.add('bar-swap');
bars[i].style.height = `${j}%`;
if (bars[i].classList.contains('show-value')) {
bars[i].querySelector('.array-bar-value').innerText = j;
}
playNote(400 + j * 5, 'triangle');
}
}
swapsCount++;
updateStats();
await sleep();
checkAbort();
if (step.type === 'swap') {
if (bars[i]) bars[i].classList.remove('bar-swap');
if (bars[j]) bars[j].classList.remove('bar-swap');
} else {
if (bars[i]) bars[i].classList.remove('bar-swap');
}
}
else if (step.type === 'sorted') {
const [i] = step.indices;
if (bars[i]) {
bars[i].classList.add('bar-sorted');
bars[i].classList.remove('bar-compare', 'bar-swap');
playNote(600 + (array[i] || 10) * 5, 'square');
}
await sleep();
}
else if (step.type === 'count_init') {
// Setup secondary rendering area for counting sort
const countArr = step.array;
countArrayContainer.style.display = 'flex';
countArrayContainer.innerHTML = '';
countBars = [];
const containerWidth = countArrayContainer.clientWidth;
const barWidth = Math.max(1, (containerWidth / countArr.length) - 2);
for (let k = 0; k < countArr.length; k++) {
const bar = document.createElement('div');
bar.classList.add('array-bar');
bar.style.height = `5%`; // initially tiny or based on max count
bar.style.width = `${barWidth}px`;
if (barWidth > 20) {
bar.classList.add('show-value');
const valSpan = document.createElement('span');
valSpan.classList.add('array-bar-value');
valSpan.innerText = countArr[k];
bar.appendChild(valSpan);
}
countArrayContainer.appendChild(bar);
countBars.push({ el: bar, val: countArr[k] });
}
}
else if (step.type === 'count_update') {
const [idx, val, maxCount] = step.indices;
if (countBars[idx]) {
countBars[idx].el.classList.add('bar-swap');
countBars[idx].val = val;
// Height based on proportion of maxCount
const heightPct = maxCount === 0 ? 5 : Math.max(5, (val / maxCount) * 95);
countBars[idx].el.style.height = `${heightPct}%`;
if (countBars[idx].el.classList.contains('show-value')) {
countBars[idx].el.querySelector('.array-bar-value').innerText = val;
}
playNote(200 + val * 20);
await sleep();
checkAbort();
countBars[idx].el.classList.remove('bar-swap');
}
}
}
}
function updateStats() {
comparisonsCountEl.innerText = comparisonsCount;
swapsCountEl.innerText = swapsCount;
}
// --- Controller Actions ---
async function startSorting() {
if (isSorting) return;
isSorting = true;
isPaused = false;
// UI Update
generateBtn.disabled = true;
startBtn.disabled = true;
algoSelect.disabled = true;
sizeSlider.disabled = true;
pauseBtn.disabled = false;
resetBtn.disabled = false;
pauseBtn.innerText = "Pause";
stepBtn.disabled = true;
// Reset sorted classes if array was previously sorted and not generated anew
bars.forEach(b => {
b.classList.remove('bar-sorted', 'bar-compare', 'bar-swap');
});
// Create abort controller
abortController = new AbortController();
try {
const algo = algoSelect.value;
let steps = [];
const arrayCopy = [...array];
// Call the appropriate algorithm to generate steps
switch(algo) {
case 'bubble': steps = bubbleSort(arrayCopy); break;
case 'selection': steps = selectionSort(arrayCopy); break;
case 'insertion': steps = insertionSort(arrayCopy); break;
case 'merge': steps = mergeSort(arrayCopy); break;
case 'quick': steps = quickSort(arrayCopy); break;
case 'heap': steps = heapSort(arrayCopy); break;
case 'counting': steps = countingSort(arrayCopy); break;
case 'radix': steps = radixSort(arrayCopy); break;
}
// Execute generated steps
await executeSteps(steps);
// Final polish - make sure all are green if completed successfully
for (let i = 0; i < bars.length; i++) {
bars[i].classList.add('bar-sorted');
}
playNote(800, 'sine');
} catch (e) {
if (e.message !== 'Animation Aborted') {
console.error(e);
}
} finally {
isSorting = false;
generateBtn.disabled = false;
startBtn.disabled = false;
algoSelect.disabled = false;
sizeSlider.disabled = false;
pauseBtn.disabled = true;
stepBtn.disabled = true;
}
}
function stopSorting() {
if (abortController) {
abortController.abort();
}
isSorting = false;
isPaused = false;
if (currentResolvePause) currentResolvePause(); // release if paused
generateBtn.disabled = false;
startBtn.disabled = false;
algoSelect.disabled = false;
sizeSlider.disabled = false;
pauseBtn.disabled = true;
resetBtn.disabled = true;
stepBtn.disabled = true;
pauseBtn.innerText = "Pause";
// Quick regenerate to cleanup
generateNewArray();
}
function togglePause() {
isPaused = !isPaused;
if (isPaused) {
pauseBtn.innerText = "Resume";
pauseBtn.classList.replace('btn-warning', 'btn-success');
stepBtn.disabled = false;
} else {
pauseBtn.innerText = "Pause";
pauseBtn.classList.replace('btn-success', 'btn-warning');
stepBtn.disabled = true;
if (currentResolvePause) {
currentResolvePause();
currentResolvePause = null;
}
}
}
function nextStep() {
if (isPaused && currentResolvePause) {
// Resolve the pause temporarily, but remain paused for the next step iteration
const tempResolve = currentResolvePause;
currentResolvePause = null;
tempResolve();
}
}
// --- UI Updates ---
function updateAlgorithmInfo() {
const algo = algoSelect.value;
const details = ALGO_DETAILS[algo];
algoTitle.innerText = details.title;
algoDescription.innerText = details.description;
timeBest.innerText = details.time.best;
timeAverage.innerText = details.time.avg;
timeWorst.innerText = details.time.worst;
spaceWorst.innerText = details.space;
}
// --- Event Listeners ---
window.onload = () => {
updateSpeed();
updateAlgorithmInfo();
generateNewArray();
};
sizeSlider.addEventListener('input', () => {
sizeValue.innerText = sizeSlider.value;
generateNewArray();
});
speedSlider.addEventListener('input', updateSpeed);
algoSelect.addEventListener('change', () => {
updateAlgorithmInfo();
generateNewArray();
});
generateBtn.addEventListener('click', generateNewArray);
startBtn.addEventListener('click', startSorting);
pauseBtn.addEventListener('click', togglePause);
stepBtn.addEventListener('click', nextStep);
resetBtn.addEventListener('click', stopSorting);
toggleThemeBtn.addEventListener('click', () => {
const body = document.body;
if (body.getAttribute('data-theme') === 'dark') {
body.setAttribute('data-theme', 'light');
moonIcon.style.display = 'none';
sunIcon.style.display = 'block';
} else {
body.setAttribute('data-theme', 'dark');
moonIcon.style.display = 'block';
sunIcon.style.display = 'none';
}
});
toggleSoundBtn.addEventListener('click', () => {
isSoundOn = !isSoundOn;
if (isSoundOn) {
soundOnIcon.style.display = 'block';
soundOffIcon.style.display = 'none';
} else {
soundOnIcon.style.display = 'none';
soundOffIcon.style.display = 'block';
}
});
// Windows resize handling for responsiveness of bars
let resizeTimeout;
window.addEventListener('resize', () => {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(() => {
if (!isSorting) {
generateNewArray();
}
}, 200);
});