Sorting illustration - Quick 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(left, right){
   let len = data.length;
   let pivot;
   let partitionIndex;


  if(left < right){
    pivot = right;
    partitionIndex = partition(pivot, left, right);
    
   //sort left and right
   draw();
   
   requestAnimationFrame(() => sort(left, partitionIndex - 1));
   requestAnimationFrame(() => sort(partitionIndex + 1, right));
  }
}

function swap(i, j){
   var temp = data[i];
   data[i] = data[j];
   data[j] = temp;
}

function partition(pivot, left, right){
   let pivotValue = data[pivot];
   let partitionIndex = left;

   for(let i = left; i < right; i++){
    if(data[i] < pivotValue){
      swap(i, partitionIndex);
      partitionIndex++;
    }
  }
  
  swap(right, partitionIndex);
  
  return partitionIndex;
}

setTimeout(() => requestAnimationFrame(() => sort(0, data.length - 1)), 1000);