Sorting illustration - Insertion sort
by Julien Roche
HTML
<canvas></canvas>
CSS
html, body {
border: none;
height: 100%;
margin: 0px 0px 0px 0px;
overflow: hidden;
padding: 0px 0px 0px 0px;
width: 100%;
}
Babel + JSX
// Generate data
let data = [];
for(let i = 0; i < 1000; ++i) {
data.push(Math.random());
}
// Display data
let canvasElement = document.querySelector('canvas');
let context = canvasElement.getContext('2d');
function draw() {
context.fillStyle = 'black';
context.fillRect(0, 0, canvasElement.width, canvasElement.height);
context.fillStyle = 'white';
let columnWidth = Math.floor(canvasElement.width / data.length);
for (const [index, value] of data.entries()) {
context.fillRect(columnWidth * index, canvasElement.height - Math.round(canvasElement.height * value), columnWidth, canvasElement.height);
}
}
function resize() {
let { height, width } = document.body.getBoundingClientRect();
canvasElement.height = height;
canvasElement.width = width;
draw();
}
window.addEventListener('resize', resize);
resize();
// Sort data
function sort(idx) {
let minIdx = idx ? idx : 0;
let i = idx ? idx : 0;
let temp;
let len = data.length;
if (minIdx >= len) {
alert('This is the end!');
} else {
for(let j = i + 1; j < len; ++j){
if(data[j] < data[minIdx]){
minIdx = j;
}
}
temp = data[i];
data[i] = data[minIdx];
data[minIdx] = temp;
draw();
requestAnimationFrame(() => sort(i + 1))
}
}
setTimeout(() => requestAnimationFrame(() => sort(0)), 1000);