Repository navigation
Expand file tree
/
Copy pathbubble_sort.html
More file actions
559 lines (520 loc) · 16.3 KB
/
Copy pathbubble_sort.html
File metadata and controls
559 lines (520 loc) · 16.3 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
<title>Bubble Sort</title>
<link rel="stylesheet" href="demo-theme.css" />
<style>
:root {
--page-max-width: 1360px;
--console-cols: 1fr 1fr;
}
/* ---- stage: array as bars ---- */
.stage {
position: relative;
height: 240px;
background:
linear-gradient(var(--line) 1px, transparent 1px) 0 0 / 100% 20%,
var(--surface-sunken);
background-repeat: no-repeat, repeat;
border-radius: 8px;
border: 1px solid var(--line);
overflow: hidden;
}
.bar {
position: absolute;
bottom: 0;
height: 100%;
display: flex;
flex-direction: column-reverse;
align-items: center;
transition: transform 220ms cubic-bezier(0.4, 0, 0.2, 1);
will-change: transform;
}
.bar-index {
font-family: var(--mono);
font-size: 0.68rem;
color: var(--ink-faint);
padding-bottom: 4px;
}
.bar-fill {
width: 100%;
border-radius: 4px 4px 2px 2px;
background: var(--accent);
transition:
background-color 200ms ease,
box-shadow 200ms ease;
}
.bar.is-active .bar-fill {
background: var(--active);
box-shadow: 0 0 0 2px var(--active) inset;
}
.bar.is-swap-flash .bar-fill {
animation: swapFlash 420ms ease-out;
}
@keyframes swapFlash {
0% {
filter: brightness(1);
}
35% {
filter: brightness(1.8);
}
100% {
filter: brightness(1);
}
}
.bar.is-sorted .bar-fill {
background: var(--sorted);
}
.bar-value {
font-family: var(--mono);
font-size: 0.7rem;
font-weight: 600;
color: var(--ink-dim);
padding-bottom: 3px;
font-variant-numeric: tabular-nums;
}
.bar.is-active .bar-value {
color: var(--active);
}
.bar-caret {
font-size: 0.6rem;
color: var(--active);
opacity: 0;
transform: translateY(2px);
transition:
opacity 160ms ease,
transform 160ms ease;
padding-bottom: 1px;
}
.bar.is-active .bar-caret {
opacity: 1;
transform: translateY(0);
}
</style>
<div class="page">
<header>
<div class="header-copy">
<div class="eyebrow">Algorithm Visualizer</div>
<h1>Bubble Sort</h1>
<p class="lede">
Bubble sort repeatedly walks the array, comparing each pair of neighbors
and swapping them when they're out of order. Larger values "bubble"
toward the end with every pass, so each full pass needs to check one
fewer element than the last.
</p>
<div class="specs">
<span class="spec"
><span data-icon="badge-time"></span><b>Time</b> O(n²) avg & worst
· O(n) best</span
>
<span class="spec"
><span data-icon="badge-space"></span><b>Space</b> O(1)</span
>
<span class="spec"><b>Stable</b> yes</span>
<span class="spec"><b>In-place</b> yes</span>
</div>
</div>
<button type="button" class="theme-toggle" id="themeToggle">
<span data-icon="sun"></span>
<span class="theme-toggle-label">Light</span>
</button>
</header>
<div class="console">
<section class="panel">
<div class="panel-head">
<span class="panel-title">Stage</span>
<span class="status" id="status">Ready — press Play or Step</span>
</div>
<div class="stage-wrap">
<div class="stage" id="stage"></div>
<div class="legend">
<span><span class="dot accent"></span>unsorted</span>
<span><span class="dot active"></span>comparing</span>
<span><span class="dot sorted"></span>sorted</span>
</div>
</div>
<div class="controls">
<div class="control-buttons">
<button id="btnPlay" class="primary">Play</button>
<button id="btnStep">Step</button>
<button id="btnReset">Reset</button>
<button id="btnShuffle">Shuffle</button>
</div>
<div class="control-sliders">
<div class="slider-group">
<div class="slider-label-row"><span>Size</span></div>
<input
type="range"
id="size"
min="5"
max="30"
value="15"
step="5"
/>
<div class="slider-value" id="sizeValue">15 bars</div>
</div>
<div class="slider-group">
<div class="slider-label-row">
<span>Slow</span><span>Fast</span>
</div>
<input
type="range"
id="speed"
min="100"
max="800"
value="400"
step="100"
/>
<div class="slider-value" id="speedValue">400 ms / step</div>
</div>
</div>
</div>
<div class="stats">
<div class="stat">
<div class="stat-label">Comparisons</div>
<div class="stat-value" id="statCompare">0</div>
</div>
<div class="stat">
<div class="stat-label">Swaps</div>
<div class="stat-value" id="statSwap">0</div>
</div>
<div class="stat">
<div class="stat-label">Pass</div>
<div class="stat-value" id="statPass">0 / 0</div>
</div>
</div>
</section>
<section class="panel">
<div class="lang-tabs" id="langTabs"></div>
<div class="panel-head">
<span class="panel-title" id="codeFilename"
>javascript/code/sort/bubbleSort.js</span
>
</div>
<div class="code" id="code"></div>
</section>
</div>
<div aria-hidden="true" style="height: 2rem"></div>
</div>
<script src="icons.js"></script>
<script src="demo-engine.js"></script>
<script>
(function () {
"use strict";
window.Icons.mount();
window.Icons.mount();
DemoEngine.initTheme("bubble-sort");
var LANGS = {
js: {
label: "JS",
icon: "lang-js",
file: "javascript/code/sort/bubbleSort.js",
keywords: ["function", "let", "for", "if"],
lines: [
{ text: "function bubbleSort(arr) {" },
{ text: " let len = arr.length;" },
{ text: " for (let i = 0; i < len; i++) {", group: "for-i" },
{
text: " for (let j = 0; j < len - i - 1; j++) {",
group: "for-j",
},
{ text: " if (arr[j] > arr[j + 1]) {", group: "if-compare" },
{
text: " [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];",
group: "swap",
},
{ text: " }" },
{ text: " }" },
{ text: " }" },
{ text: "}" },
],
},
csharp: {
label: "C#",
icon: "lang-csharp",
file: "csharp/Code/Sort/BubbleSort.cs",
keywords: ["public", "class", "static", "void", "int", "for", "if"],
lines: [
{ text: "public class BubbleSort" },
{ text: "{" },
{ text: " public static void Sort(int[] arr)" },
{ text: " {" },
{
text: " for (int i = 0; i < arr.Length - 1; i++)",
group: "for-i",
},
{ text: " {", group: "for-i" },
{
text: " for (int j = 0; j < arr.Length - i - 1; j++)",
group: "for-j",
},
{ text: " {", group: "for-j" },
{
text: " if (arr[j] > arr[j + 1])",
group: "if-compare",
},
{ text: " {", group: "if-compare" },
{
text: " (arr[j + 1], arr[j]) = (arr[j], arr[j + 1]);",
group: "swap",
},
{ text: " }" },
{ text: " }" },
{ text: " }" },
{ text: " }" },
{ text: "}" },
],
},
java: {
label: "Java",
icon: "lang-java",
file: "java/src/main/java/sort/BubbleSort.java",
keywords: ["public", "class", "static", "void", "int", "for", "if"],
lines: [
{ text: "public class BubbleSort {" },
{ text: " public static void sort(int[] arr) {" },
{
text: " for (int i = 0; i < arr.length; i++) {",
group: "for-i",
},
{
text: " for (int j = 0; j < (arr.length - 1 - i); j++) {",
group: "for-j",
},
{
text: " if (arr[j] > arr[j + 1]) {",
group: "if-compare",
},
{ text: " int temp = arr[j];", group: "swap" },
{ text: " arr[j] = arr[j + 1];", group: "swap" },
{ text: " arr[j + 1] = temp;", group: "swap" },
{ text: " }" },
{ text: " }" },
{ text: " }" },
{ text: " }" },
{ text: "}" },
],
},
python: {
label: "Python",
icon: "lang-python",
file: "python/code/sort/bubble_sort.py",
keywords: ["def", "for", "in", "if", "range", "len"],
lines: [
{ text: "def sort(arr):" },
{ text: " for i in range(len(arr)):", group: "for-i" },
{ text: " for j in range(len(arr)-i-1):", group: "for-j" },
{ text: " if arr[j] > arr[j+1]:", group: "if-compare" },
{
text: " arr[j], arr[j+1] = arr[j+1], arr[j]",
group: "swap",
},
],
},
go: {
label: "Go",
icon: "lang-go",
file: "go/code/sort/bubble_sort.go",
keywords: ["package", "func", "for", "if", "range", "len"],
lines: [
{ text: "package sort" },
{ text: "" },
{ text: "func BubbleSort(arr []int) {" },
{ text: " for i := range arr {", group: "for-i" },
{ text: " for j := range len(arr) - i - 1 {", group: "for-j" },
{ text: " if arr[j] > arr[j + 1] {", group: "if-compare" },
{
text: " arr[j], arr[j + 1] = arr[j + 1], arr[j]",
group: "swap",
},
{ text: " }" },
{ text: " }" },
{ text: " }" },
{ text: "}" },
],
},
};
var codePanel = DemoEngine.mountCodePanel({
langs: LANGS,
order: ["js", "csharp", "java", "python", "go"],
defaultLang: "js",
codeEl: document.getElementById("code"),
filenameEl: document.getElementById("codeFilename"),
tabsEl: document.getElementById("langTabs"),
});
var stageEl = document.getElementById("stage");
var statusEl = document.getElementById("status");
var statCompare = document.getElementById("statCompare");
var statSwap = document.getElementById("statSwap");
var statPass = document.getElementById("statPass");
var N = Number(document.getElementById("size").value);
var GAP = 6;
var MAX_BAR_H = 176;
var order = []; // current live arrangement of bar objects, mirrors `arr`
var comparisons = 0;
var swaps = 0;
function randomValues(n) {
var vals = [];
for (var k = 0; k < n; k++) vals.push(8 + Math.floor(Math.random() * 90));
return vals;
}
function buildBars(values) {
stageEl.innerHTML = "";
order = values.map(function (v, idx) {
var el = document.createElement("div");
el.className = "bar";
var idxLabel = document.createElement("span");
idxLabel.className = "bar-index";
idxLabel.textContent = String(idx);
var fill = document.createElement("div");
fill.className = "bar-fill";
fill.style.height = Math.round((v / 98) * MAX_BAR_H) + "px";
var valueLabel = document.createElement("span");
valueLabel.className = "bar-value";
valueLabel.textContent = v;
var caret = document.createElement("span");
caret.className = "bar-caret";
caret.textContent = "▲";
el.appendChild(idxLabel);
el.appendChild(fill);
el.appendChild(valueLabel);
el.appendChild(caret);
stageEl.appendChild(el);
return { value: v, el: el };
});
layout();
}
function layout() {
var stageWidth = stageEl.clientWidth;
var gap = N > 20 ? 3 : N > 15 ? 4 : GAP;
var barWidth = (stageWidth - gap * (N - 1)) / N;
order.forEach(function (bar, idx) {
bar.el.style.width = barWidth + "px";
bar.el.style.transform =
"translateX(" + Math.round(idx * (barWidth + gap)) + "px)";
});
}
function clearActive() {
order.forEach(function (bar) {
bar.el.classList.remove("is-active");
});
}
function flashSwap(bar) {
bar.el.classList.remove("is-swap-flash");
void bar.el.offsetWidth;
bar.el.classList.add("is-swap-flash");
}
function setStatus(html) {
statusEl.innerHTML = html;
}
function* bubbleSortSteps() {
var len = order.length;
for (var i = 0; i < len; i++) {
for (var j = 0; j < len - i - 1; j++) {
yield { type: "compare", i: i, j: j };
if (order[j].value > order[j + 1].value) {
var tmp = order[j];
order[j] = order[j + 1];
order[j + 1] = tmp;
yield { type: "swap", i: i, j: j };
}
}
yield { type: "pass-done", i: i };
}
yield { type: "done" };
}
function applyStep(step) {
if (step.type === "compare") {
clearActive();
var a = order[step.j],
b = order[step.j + 1];
a.el.classList.add("is-active");
b.el.classList.add("is-active");
codePanel.highlightLine("if-compare");
comparisons++;
statCompare.textContent = comparisons;
statPass.textContent = step.i + 1 + " / " + order.length;
setStatus(
'Comparing index <span class="hl">' +
step.j +
'</span> and <span class="hl">' +
(step.j + 1) +
"</span> — " +
a.value +
" vs " +
b.value,
);
return false;
} else if (step.type === "swap") {
codePanel.highlightLine("swap");
swaps++;
statSwap.textContent = swaps;
layout();
flashSwap(order[step.j]);
flashSwap(order[step.j + 1]);
setStatus(
'Swapped — <span class="hl">' +
order[step.j].value +
'</span> and <span class="hl">' +
order[step.j + 1].value +
"</span> traded places",
);
return false;
} else if (step.type === "pass-done") {
clearActive();
codePanel.highlightLine("for-i");
var sortedIdx = order.length - 1 - step.i;
order[sortedIdx].el.classList.add("is-sorted");
setStatus(
"Pass " +
(step.i + 1) +
' complete — index <span class="ok">' +
sortedIdx +
"</span> locked in",
);
return false;
} else if (step.type === "done") {
clearActive();
order.forEach(function (bar) {
bar.el.classList.add("is-sorted");
});
codePanel.highlightLine(null);
setStatus(
'<span class="ok">Sorted</span> — ' +
comparisons +
" comparisons, " +
swaps +
" swaps",
);
return true;
}
}
DemoEngine.createPlayer({
btnPlay: document.getElementById("btnPlay"),
btnStep: document.getElementById("btnStep"),
btnReset: document.getElementById("btnReset"),
btnShuffle: document.getElementById("btnShuffle"),
speedInput: document.getElementById("speed"),
speedValueEl: document.getElementById("speedValue"),
sizeInput: document.getElementById("size"),
sizeValueEl: document.getElementById("sizeValue"),
sizeLabel: function (n) {
return n + " bars";
},
randomValues: randomValues,
onReset: function (values) {
N = values.length;
comparisons = 0;
swaps = 0;
statCompare.textContent = "0";
statSwap.textContent = "0";
statPass.textContent = "0 / " + values.length;
codePanel.highlightLine(null);
setStatus("Ready — press Play or Step");
buildBars(values);
},
createGenerator: function () {
return bubbleSortSteps();
},
applyStep: applyStep,
});
window.addEventListener("resize", layout);
})();
</script>