-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
66 lines (57 loc) · 1.83 KB
/
main.js
File metadata and controls
66 lines (57 loc) · 1.83 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
import { sleep, updateBars } from './utils.js';
import * as Bubble from './algorithms/bubbleSort.js';
import * as Selection from './algorithms/selectionSort.js';
import * as Insertion from './algorithms/insertionSort.js';
import * as Merge from './algorithms/mergeSort.js';
import * as Quick from './algorithms/quickSort.js';
import * as Heap from './algorithms/heapSort.js';
const algorithms = {
bubble: Bubble,
selection: Selection,
insertion: Insertion,
merge: Merge,
quick: Quick,
heap: Heap
};
let array = [];
let stopRequested = false;
window.generateArray = function () {
const input = document.getElementById('user-input').value;
if (input && input.trim().length > 0) {
array = input.split(',').map(x => parseInt(x.trim())).filter(x => !isNaN(x));
} else {
array = Array.from({ length: 30 }, () => Math.floor(Math.random() * 400) + 20);
}
renderArray();
};
function renderArray() {
const container = document.getElementById('bars-container');
container.innerHTML = '';
array.forEach(height => {
const bar = document.createElement('div');
bar.classList.add('bar');
bar.style.height = `${height}px`;
const label = document.createElement('span');
label.innerText = height;
bar.appendChild(label);
container.appendChild(bar);
});
}
window.sort = async function () {
stopRequested = false;
const algorithm = document.getElementById('algorithm').value;
const speed = parseInt(document.getElementById('speed').value);
const bars = document.getElementsByClassName('bar');
if (algorithms[algorithm]?.sort) {
await algorithms[algorithm].sort(array, bars, speed, () => stopRequested);
updateBars(bars, array);
if (!stopRequested) {
for (let bar of bars) {
bar.classList.add('sorted');
}
}
}
};
window.stopSort = function () {
stopRequested = true;
};