Created
March 22, 2023 18:54
-
-
Save bernhardfritz/b054bea1826babe6ea1b42863eb059f9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import p8g, { | |
| background, | |
| createCanvas, | |
| height, | |
| line, | |
| noSmooth, | |
| random, | |
| } from 'https://unpkg.com/p8g.js'; | |
| const partition = (a, lo, hi) => { | |
| const pivot = a[hi]; | |
| let i = lo - 1; | |
| for (let j = lo; j <= hi - 1; j++) { | |
| if (a[j] <= pivot) { | |
| i = i + 1; | |
| [a[i], a[j]] = [a[j], a[i]]; | |
| } | |
| } | |
| i = i + 1; | |
| [a[i], a[hi]] = [a[hi], a[i]]; | |
| return i; | |
| } | |
| const quicksort = (a, lo = 0, hi = a.length - 1) => { | |
| if (lo >= hi || lo < 0) { | |
| return a; | |
| } | |
| const p = partition(a, lo, hi); | |
| quicksort(a, lo, p - 1); | |
| quicksort(a, p + 1, hi); | |
| 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(quicksort, 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