Sorting illustration - Bubble 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() {
  let swapped = false;
  for (let i = 0; i < data.length - 1; ++i) {
    if (data[i] > data[i+1]) {
      let temp = data[i];
      data[i] = data[i+1];
      data[i+1] = temp;
      swapped = true;
    }
  }
  
  draw();

  if (swapped) {
    requestAnimationFrame(sort);
    
  } else {
  	alert('This is the end!');
  }
}

setTimeout(() => requestAnimationFrame(sort), 1000);