Skip to content

Instantly share code, notes, and snippets.

@bernhardfritz
Created March 22, 2023 16:08
Show Gist options
  • Select an option

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

Select an option

Save bernhardfritz/7b6c7c25a1b6a0e9a48c75f89f5ac70b to your computer and use it in GitHub Desktop.
import p8g, {
background,
createCanvas,
height,
line,
noSmooth,
random,
} from 'https://unpkg.com/p8g.js';
const iParent = (i) => Math.floor((i - 1) / 2);
const iLeftChild = (i) => 2 * i + 1;
const iRightChild = (i) => 2 * i + 2;
const siftDown = (a, start, end) => {
let root = start;
while (iLeftChild(root) <= end) {
const child = iLeftChild(root);
let swap = root;
if (a[swap] < a[child]) {
swap = child;
}
if (child + 1 <= end && a[swap] < a[child + 1]) {
swap = child + 1;
}
if (swap === root) {
return;
} else {
[a[root], a[swap]] = [a[swap], a[root]];
root = swap;
}
}
}
const heapify = (a, count) => {
let start = iParent(count - 1);
while (start >= 0) {
siftDown(a, start, count - 1);
start = start - 1;
}
}
const heapSort = (a, count = a.length) => {
heapify(a, count);
let end = count - 1;
while (end > 0) {
[a[end], a[0]] = [a[0], a[end]];
end = end - 1;
siftDown(a, 0, end);
}
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(heapSort, 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