-
Notifications
You must be signed in to change notification settings - Fork 3
/
sorting.html
373 lines (323 loc) · 14.4 KB
/
sorting.html
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
<html>
<head>
<title>Listen and visualize sorting algorithms</title>
<meta property="og:title" content="Listen and visualize sorting algorithms">
<meta name="author" content="Usama">
<meta property="og:locale" content="en_US">
<meta property="og:description" content="Sorting Algorithms with Sound">
<meta property="og:image" content="https://smusamashah.github.io/VisualizingSorts/screenshot3.png">
<meta property="og:type" content="demo">
<meta name="google-site-verification" content="fcsy6xwzGDIwyzoNhlebWTJvbkmQNzPNwrpy0YpIqHI" />
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-8113893-21"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-8113893-21');
</script>
</head>
<body>
<style>
#container {
height: 100%;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
margin: 0;
}
#cvs {
box-shadow: 0px -7px 300px 3px rgb(46, 46, 46);
}
</style>
<div id="container">
<canvas id="cvs" width="512" height="512"></canvas>
<div id="algonames"></div>
</div>
<div style="position: fixed; top: 15px; left: 15px; width: 400px; height: 400px">
<textarea id="mySort" style="width: 400px; height: 400px">
async function shellSort(arr, draw) {
const n = arr.length;
const gaps = [15, 10, 1];
let _c = 0, _c2 = 0;
for (let g = 0; g < gaps.length; g++) {
const gap = gaps[g];
for (let i = gap; i < n; i++) {
const temp = arr[i];
let j = i
while (j >= gap && arr[j - gap] > temp) {
arr[j] = arr[j - gap];
await draw(arr, 3, j);
j -= gap;
_c++;
}
arr[j] = temp;
draw(arr, 3, j);
_c2++;
await draw(arr, 2);
}
await draw(arr, 1);
}
}
</textarea>
<button onClick="generateLink()">Generate share link</button><a id="share_link" href="#"></a>
<script type="text/javascript">
function generateLink() {
let algoInURLForm = LZString.compressToEncodedURIComponent(document.getElementById("mySort").value);
let link = document.getElementById("share_link");
link.text = "copy this link";
link.href = `${window.location.origin}${window.location.pathname}#${algoInURLForm}`;
link.onclick=()=>{window.location.hash = algoInURLForm; window.location.reload();};
}
document.addEventListener('DOMContentLoaded', () => {
if (window.location.hash && window.location.hash.length > 1) {
let algoCode = decodeURI(window.location.hash.substring(1));
document.getElementById("mySort").value = LZString.decompressFromEncodedURIComponent(algoCode);
document.getElementById("mySort").dispatchEvent(new Event("input"));
}
});
</script>
<div>
<b>await draw(arr, detail_level [, ...array_indexes]).</b><br/>
<b>arr</b>: shuffled array of positive integers<br/>
<b>detail_level</b>: 1|2|3. Used by "Detail" in control panel.<br/>
<b>array_indexes</b>: (optional) draw only these indexes. <br/>
Draw whole array if no index specified.<br/>
Can use `swap(arr, index1, index2)` to swap elements of array.<br/>
<a href="https://github.com/SMUsamaShah/VisualizingSorts">GitHub</a>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.3/dat.gui.js"></script>
<script src="./util.js"></script>
<script src="./algos.js"></script>
<script src="./lz-string.min.js"></script>
<script type="text/javascript">
var wizSorting = new WizSorting();
var gui = new dat.GUI();
gui.add(wizSorting, 'audio').name("Sound (ugly)");
gui.add(wizSorting, 'arraySize', 8, 512, 8).name("Size");
gui.add(wizSorting, 'stepDelay', 1, 1000, 1).name("Delay(ms)");
gui.add(wizSorting, 'detail', 1, 3, 1).name("Detail");
gui.add(wizSorting, 'color_map', Object.keys(wizSorting.color_maps)).name("Color Scheme");
// list all algos
wizSorting.algos.forEach((v, i)=>{
gui.add(wizSorting.algos[i], 'enabled').name(v.name);
});
gui.add(wizSorting, 'main').name("Start");
gui.add(wizSorting, 'stop').name("Stop");
//wizSorting.main();
function WizSorting() {
var _this = this; // damn callbacks
var MAX_GRID_SIZE = 512; // even this is too slow
this.audio = false;
this.ph = 8; // point height
this.pw = 8; // point width
this.arraySize = 128;
this.stepDelay = 10;
this.max = this.arraySize;
this.detail = 3;
this.color_map = 'magma';
let reset = true;
let repeatCount = 0;
// functions
this.main = start;
this.stop = stop;
this.onSortsFinished = onAllSortingFinished;
this.algos = [
{ name: "Custom", fn: (arr, draw_fn)=>{}, enabled: true},
{ name: "Bubble Sort", fn: bubbleSort, enabled: false },
{ name: "Cocktail Sort", fn: cocktailSort, enabled: false },
{ name: "Insertion Sort", fn: insertionSort, enabled: false },
{ name: "Gnome Sort", fn: gnomeSort, enabled: false },
{ name: "Comb Sort", fn: combSort, enabled: false },
{ name: "Shell Sort", fn: shellSort, enabled: false },
{ name: "Selection Sort", fn: selectionSort, enabled: false },
{ name: "Merge Sort", fn: mergeSort, enabled: false },
{ name: "Parallel Merge Sort", fn: parallelMergeSort, enabled: false },
{ name: "Radix Sort", fn: radixSort, enabled: false },
{ name: "Quick Sort", fn: quickSort, enabled: false },
{ name: "Odd-Even Sort", fn: oddEvenSort, enabled: false },
{ name: "Cycle Sort", fn: cycleSort, enabled: false },
{ name: "Heap Sort", fn: heapSort, enabled: false },
// _this.oddEvenSort2 ? Sorting.oddEvenSort2 : null,
];
const mySortTextBox = document.getElementById("mySort");
mySortTextBox.oninput = update_my_sort;
function update_my_sort(e) {
eval(`_this.algos[0].fn = ${mySortTextBox.value}`);
}
update_my_sort();
var audioCtx;
var _ctx, ctx;
var _canvas, offscreenCanvas; // offscreen canvas for faster rendering
this.color_maps = {
hsl: function (x, max) {
let j = rescale(x, 0, max, 0, 360);
return "hsl(" + (j) + ", 50%, 50%)";
},
grayscale: function (x, max) {
let j = rescale(x, 0, max, 0, 255);
return 'rgb(' + [j, j, j].join() + ')';
},
magma: function (x, max) {
let j = rescale(x, 0, max, 0, 360);
return `hsl(${j * 0.5 + 250},${50}%,${50 * j / 180}%)`;
}
};
// init
(function () {
audioCtx = new AudioContext();
_canvas = document.getElementById("cvs");
_canvas.setAttribute("width", MAX_GRID_SIZE);
_canvas.setAttribute("height", MAX_GRID_SIZE);
_ctx = _canvas.getContext("2d", { alpha: false }); // on screen context
// everything will be rendered on this off-screen canvas
if (typeof(window.OffscreenCanvas) != "undefined") {
// chromium only
offscreenCanvas = new OffscreenCanvas(MAX_GRID_SIZE, MAX_GRID_SIZE);
} else {
offscreenCanvas = document.createElement("canvas");
offscreenCanvas.width = MAX_GRID_SIZE;
offscreenCanvas.height = MAX_GRID_SIZE;
}
ctx = offscreenCanvas.getContext('2d');
// and will be copied to on-screen canvas in requestAnimationFrame
_this.ph = _this.pw = MAX_GRID_SIZE / _this.arraySize;
for (let i = 0; i < _this.arraySize; i++) {
drawPoint(i, 0, i * _this.ph, MAX_GRID_SIZE, _this.ph)
}
})();
function renderLoop() {
// let bitmap = offCanvas.transferToImageBitmap();
// _ctx.transferFromImageBitmap(bitmap);
// copy from offscreen canvas to onscreen canvas
_ctx.drawImage(ctx.canvas, 0, 0);
requestAnimationFrame(renderLoop);
}
renderLoop();
// var recorder = new CanvasRecorder(_canvas);
function start() {
reset = true;
_this.max = _this.arraySize;
_this.ph = _this.pw = MAX_GRID_SIZE / _this.arraySize;
// recorder.start();
reset = false;
let numbers = (new Int32Array(_this.arraySize))
.fill(0, 0, _this.arraySize)
.map(function (v, i) { return i + 1; });
// selected sorts
let selectedAlgos = _this.algos.filter(v => v.enabled == true);
if (selectedAlgos.length == 0) {
return;
}
// algo labels
let el = document.getElementById("algonames");
if (el) {
el.innerText = "";
selectedAlgos.forEach((sort, i) => {
el.innerText += sort.name;
if (i < selectedAlgos.length - 1)
el.innerText += " | ";
});
}
repeatCount = Math.ceil(_this.arraySize / selectedAlgos.length);
// create arrays for algos filled with randomized data
let arrays = new Array(selectedAlgos.length * repeatCount);
for (let i = 0; i < arrays.length; i++) {
arrays[i] = shuffle(numbers).slice(); // shuffled.slice();
drawArray(arrays[i], i);
}
// run algos by applying selected algo on each array
console.time("algorun");
let calls = [];
let x = 0;
for (let i = 0; i < selectedAlgos.length; i++) {
for (let j = 0; j < repeatCount; j++) {
const sortingAlgo = selectedAlgos[i].fn;
if (sortingAlgo != null)
var c = sortingAlgo(arrays[x], drawcb(x++));
calls.push(c);
}
}
Promise.all(calls).then((values)=>{
_this.onSortsFinished(values);
});
}
function drawcb(x) {
return async function draw_and_wait(arr, detail = 1, ...indexes) {
if (_this.detail != detail) return;
// draw given indexes of array
if (arguments.length <= 2) {
// draw whole array if no indexes specified
drawArray(arr, x);
} else {
// otherwise draw given index only
for (let i = 0; i < indexes.length; i++) {
const j = indexes[i];
drawPoint(arr[j], x * _this.pw, j * _this.ph, _this.pw, _this.ph);
// play the music
if (x === 0 && _this.audio) {
playAudio(j, 1.7);
}
}
}
// wait after drawing
await sleep(_this.stepDelay);
}
}
function stop () {
// if(_this.audio && osc) osc.stop();
if(reset == false) {
reset = true;
}
}
function onAllSortingFinished(e){
// console.log("Finished", e);
// recorder.stop();
// recorder.save();
console.timeEnd("algorun");
}
function playAudio(freq, time = 1.5) {
let osc = audioCtx.createOscillator();
let gain = audioCtx.createGain();
osc.connect(gain);
gain.connect(audioCtx.destination);
osc.type = 'sine';
osc.frequency.value = 500 + freq * 7;
osc.start(); // play sound
gain.gain.exponentialRampToValueAtTime(0.00001, audioCtx.currentTime + time); // reduce it gradually
setTimeout(() => osc.stop(), 300);
//o.stop();
}
// setTimeout.dt = 0;
// function selfAdjustingTimeout(callback, timeout, args) {
// setTimeout.et = (new Date).getTime() + timeout;
// let cb = () => {
// setTimeout.dt = (new Date).getTime() - setTimeout.et;
// callback();
// };
// setTimeout(cb, timeout - setTimeout.dt, args);
// }
async function sleep(ms) {
if (reset)
return Promise.reject("stopped");
// return new Promise(rs => selfAdjustingTimeout(rs, ms));
return new Promise(rs => setTimeout(rs, ms));
}
// draw array on position x
function drawArray(arr, x) {
for (let i = arr.length - 1; i >= 0; i--) {
drawPoint(arr[i], x * _this.pw, i * _this.ph, _this.pw, _this.ph);
}
}
// draw number as HSL block with constant saturation and luminence
function drawPoint(hue, x, y, w, h, highlight = false) {
let j = rescale(hue, 0, _this.max, 0, 360);
ctx.fillStyle = _this.color_maps[_this.color_map](hue, _this.max);
ctx.fillRect(x, y, w, h);
}
}
</script>
</body>
</html>