xxxxxxxxxx
80
var rectangles = 100;
var colorHue;
var backgroundColor;
function shuffle(array) {
var currentIndex = array.length,
temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
var sortableArray = [];
var bigI = rectangles - 1;
var bigJ = 1;
function setup() {
// frameRate(10);
createCanvas(1280, 720);
colorMode(HSB, 255);
colorHue = random(255);
for (var i = 0; i < rectangles; i++) {
sortableArray.push(map(i, 0, rectangles - 1, 20, height));
}
sortableArray = shuffle(sortableArray);
}
function draw() {
colorHue += 0.1;
colorHue %= 255;
bubbleSort();
background(colorHue, 255, 60);
var rectwidth = width / rectangles;
for (var i = 0; i < sortableArray.length; i++) {
fill(colorHue, 255, map(sortableArray[i], 30, height, 120, 255));
noStroke();
rect(i * rectwidth, height - sortableArray[i], rectwidth+1, sortableArray[i]);
}
textSize(20);
textAlign(LEFT, TOP)
fill(colorHue, 255, 255);
text("BUBBLE SORT", 20, 20);
if (bigI < 0) {
fill(255);
text("FINISHED", 20, 60);
}
}
function bubbleSort(){
if (bigI >= 0) {
if (bigJ > bigI) {
bigI--;
bigJ = 1;
}
if (sortableArray[bigJ - 1] > sortableArray[bigJ]) {
var temp = sortableArray[bigJ - 1];
sortableArray[bigJ - 1] = sortableArray[bigJ];
sortableArray[bigJ] = temp;
}
bigJ++;
}
}