I tried to redraw the canvas every time it swaps, but it first renders everything and then draws. I would like every Swap to redraw the canvas with the object information.
<!DOCTYPE html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<style type="text/css">
body{
margin: 0;
}
</style>
</head>
<body>
<canvas id="canvas" class="canvas" width="1400" height="750">
</canvas>
</body>
</html>
<script type="text/javascript">
const Y = 700;
const X = 50;
const size = 10;
const max_rand = 60;
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
$(document).ready(function(){
var numbers = [];
for (var i = 0; i < 121; i++) {
numbers.push({number: Math.random() * max_rand, color: getRandomColor()});
}
drawGraph(numbers);
sleep(200);
quickSort(numbers, 0, numbers.length-1);
});
function drawGraph(numbers){
ctx.clearRect(0, 0, canvas.width, canvas.height);
var x = X;
var y = Y;
for (var i = 0; i < numbers.length; i++) {
ctx.fillStyle = numbers[i].color;
for (var j = 0; j < numbers[i].number; j++) {
ctx.fillRect(x, y, size, size);
y -= size;
}
x += size;
y = Y;
}
}
function sleep(miliseconds) {
var currentTime = new Date().getTime();
while (currentTime + miliseconds >= new Date().getTime()) {
}
}
function quickSort(numbers, left, right) {
var index;
if (numbers.length > 1) {
index = partition(numbers, left, right);
if (left < index - 1) {
quickSort(numbers, left, index - 1);
}
if (index < right) {
quickSort(numbers, index, right);
}
}
return numbers;
}
function swap(numbers, firstIndex, secondIndex){
var temp = numbers[firstIndex].number;
numbers[firstIndex].number = numbers[secondIndex].number;
numbers[secondIndex].number = temp;
drawGraph(numbers);
sleep(50);
}
function partition(numbers, left, right) {
var pivot = numbers[Math.floor((right + left) / 2)].number,
i = left,
j = right;
while (i <= j) {
while (numbers[i].number < pivot) {
i++;
}
while (numbers[j].number > pivot) {
j--;
}
if (i <= j) {
swap(numbers, i, j);
i++;
j--;
}
}
return i;
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
</script>