Skip to content

Instantly share code, notes, and snippets.

@hwayne
Created December 4, 2023 17:54
Show Gist options
  • Save hwayne/85488f755066d8aa57cd147875e97b72 to your computer and use it in GitHub Desktop.
Save hwayne/85488f755066d8aa57cd147875e97b72 to your computer and use it in GitHub Desktop.
Rainbow sort
// put in https://editor.p5js.org/
// generated (mostly) with GPT4
let cols, rows;
let w = 2;
let colors = [];
let i = 0;
let j = 0;
let sorted = false;
function setup() {
createCanvas(200, 400);
cols = width / w;
rows = height / w;
// Generate random colors for each grid cell
for (let x = 0; x < cols; x++) {
for (let y = 0; y < rows; y++) {
let index = x + y * cols;
colors[index] = color(random(255), random(255), random(255));
}
}
//colorMode(HSB, 255); // Sort by hue
frameRate(30);
}
function draw() {
background(51);
// Display the colors
for (let x = 0; x < cols; x++) {
for (let y = 0; y < rows; y++) {
let index = x + y * cols;
fill(colors[index]);
noStroke();
rect(x * w, y * w, w, w);
}
}
// If not sorted, run a step of the bubble sort
if (!sorted) {
let n = cols * rows;
// Run through all elements
for (let y = 0; y < n - i - cols; y++) {
let currentHue = hue(colors[y]);
let nextHue = hue(colors[y + cols]);
// Swap elements if out of order
if (currentHue > nextHue) {
let temp = colors[y];
colors[y] = colors[y + cols];
colors[y + cols] = temp;
}
}
// Increment step
i += 1;
if (i >= n - 1) {
noLoop();
sorted = true;
}
}
}
@sohang3112
Copy link

Cool effect! (came here from the original article: https://buttondown.email/hillelwayne/archive/when-would-you-ever-want-bubblesort/)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment