Witam, mógłby mi ktoś powiedzieć czy moje rozumowanie jest poprawne? Chciałem zrobić wizualizację sortowania bąbelkowego, ale coś nie działa.
<canvas id="1" width="1000" height="1000"></canvas>
<script src="bubble.js"></script>
<button onclick="main()">posortuj</button>
grid = 10;
window.onload = function()
{
canvas = document.getElementById('1');
ctx = canvas.getContext('2d');
tablica = [1];
}
function main()
{
tablica = [];
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (i = 0;i < 100;i++)
{
tablica[i] = i + 1;
}
n = tablica.length;
shuffle(tablica);
do
{
for (i = 0;i < n - 1;i++)
{
ctx.fillStyle = 'yellow';
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (j = 0; j < tablica.length;j++)
{
me = Math.random();
if (me < 0.25)
{
ctx.fillStyle = 'red';
}
else if (me > 0.25 && me < 0.5)
{
ctx.fillStyle = 'purple';
}
else if (me > 0.5 && me < 0.75)
{
ctx.fillStyle = 'green';
}
else if (me > 0.75)
{
ctx.fillStyle = 'blue';
}
ctx.fillRect(tablica[j] * grid - grid, canvas.height - tablica[j] * grid, grid, grid);
ctx.fillStyle = 'white';
ctx.font = '8px Arial';
ctx.fillText(j + 1,tablica[j] * grid - grid, canvas.height - tablica[j] * grid + grid);
}
if (tablica[i] > tablica[i + 1])
{
temp = tablica[i];
tablica[i] = tablica[i + 1];
tablica[i + 1] = temp;
}
}
n--;
console.log(tablica);
}
while (n > 1);
}
function shuffle(array) {
var m = array.length, t, i;
// While there remain elements to shuffle…
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}