Skip to content

Instantly share code, notes, and snippets.

@bernhardfritz
Last active March 5, 2023 10:10
Show Gist options
  • Select an option

  • Save bernhardfritz/f6aff336deaa8335bae359ac133869aa to your computer and use it in GitHub Desktop.

Select an option

Save bernhardfritz/f6aff336deaa8335bae359ac133869aa to your computer and use it in GitHub Desktop.
import p8g, {
background,
createCanvas,
height,
line,
noSmooth,
random,
} from 'https://unpkg.com/p8g.js';
const selectionSort = (a) => {
const n = a.length;
for (let i = 0; i < n; i++) {
let jMin = i;
for (let j = i + 1; j < n; j++) {
if (a[j] < a[jMin]) {
jMin = j;
}
}
if (jMin != i) {
[a[i], a[jMin]] = [a[jMin], a[i]];
}
}
return a;
};
const fisherYatesShuffle = (a) => {
const n = a.length;
for (let i = 0; i < n - 2; i++) {
const j = Math.floor(random(i, n));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
};
function* makeIterator(fn, a) {
const steps = [];
const handler = {
set(target, p, newValue) {
steps.push([p, newValue]);
target[p] = newValue;
return true;
},
};
const proxy = new Proxy([...a], handler);
fn(proxy);
for (const step of steps) {
yield step;
}
}
const n = 100;
const sorted = [...Array(n).keys()];
let it, a;
const init = () => {
const unsorted = fisherYatesShuffle(sorted);
it = makeIterator(selectionSort, unsorted);
a = [...unsorted];
};
init();
p8g.draw = () => {
background(255);
noSmooth();
a.forEach((y, x) => {
line(x, height, x, height - y);
});
const { value, done } = it.next();
if (done) {
init();
} else {
const [x, y] = value;
a[x] = y;
}
};
createCanvas(n, n);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment