aboutsummaryrefslogtreecommitdiff
path: root/layouts/shortcodes/sort.html
blob: a748bd13a0a1b065130ad53b60eeef8b454c0a7e (plain)
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
<button onclick="run()">Run visualization</button>
<pre id="visualization">
</pre>
<script>
let running = false

function render(n, A, i, j) {
	let line1 = Array(n).fill(" ")
	line1[j] = "j"
	line1[i] = "i"
	document.getElementById("visualization").innerHTML = line1.join(" ") + "\n" + A.join(" ")
}

async function run() {
	if (running) return
	running = true

	let n = 10
	let A = Array(n).fill().map(() => Math.floor(Math.random() * 10))
	for (let i = 0; i < n; i++) {
		for (let j = 0; j < n; j++) {
			render(n, A, i, j)
			await new Promise(resolve => setTimeout(resolve, 500))
			if (A[i] < A[j]) {
				let tmp = A[i]
				A[i] = A[j]
				A[j] = tmp
				render(n, A, i, j)
				await new Promise(resolve => setTimeout(resolve, 500))
			}
		}
	}

	running = false
}
</script>