Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <html>

<head>
</head>

<body>
</body>

</html>
              
            
!

CSS

              
                body {
    padding: 0;
    margin: 0;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    justify-content: center;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    background: black;
}

canvas {
    position: fixed;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}

              
            
!

JS

              
                import p5 from "https://cdn.skypack.dev/p5@1.2.0";

class Sorter {
    pos: number;
    values: number[];
    p5: P5;
    sortStep: () => void;
    customeResetValues: () => void;
    isDone: boolean;
    name: String;
    iterations: number;
    constructor(p5, pos) {
        this.p5 = p5;
        this.pos = pos;
        this.values = [];
    }
    resetValues(values: number[]) {
        this.values = [...values];
        this.iterations = 0;
        this.isDone = false;
        if (typeof this.customResetValues === "function") {
            this.customResetValues();
        }
    }
    async asyncSort() {
        this.sortStep();
        /*
        if (!this.isDone) {
            this.iterations++;
            this.sortStep();
            setTimeout(() => this.asyncSort(), 100);
        }
        */
    }
    draw() {
        const p5 = this.p5;
        for (let i = 0; i < this.values.length; i++) {
            p5.textSize(15);
            p5.fill(250);
            p5.noStroke();
            p5.text(
                `${this.name} - ${this.iterations}`,
                0,
                (this.pos - 1) * SORTER_HEIGHT + 20
            );
            p5.stroke(0);
            p5.strokeWeight(1);
            if (this.isDone) {
                p5.fill("green");
            } else {
                p5.fill(250);
            }
            p5.rect(
                i * BAR_WIDTH,
                this.pos * SORTER_HEIGHT - this.values[i],
                BAR_WIDTH,
                this.values[i]
            );
        }
    }
}

class BubbleSorter extends Sorter {
    n: number;
    constructor(p5, pos) {
        super(p5, pos);
        this.name = "Bubble sort";
    }
    customResetValues() {
        this.n = this.values.length;
    }
    sortStep() {
        // If there is no remaining iterations do nothing
        if (this.n <= 1) {
            this.isDone = true;
            return;
        }

        // Swap the elements by comparing them
        for (let j = 0; j < this.n - 1; j++) {
            if (this.values[j] > this.values[j + 1]) {
                [this.values[j], this.values[j + 1]] = [
                    this.values[j + 1],
                    this.values[j]
                ];
            }
        }

        // We did one more iteration
        this.n--;
        this.iterations++;
        setTimeout(() => this.asyncSort(), ITERATION_DELAY);
    }
}

class SelectionSorter extends Sorter {
    i: number;
    constructor(p5, pos) {
        super(p5, pos);
        this.name = "Selection sort";
    }
    customResetValues() {
        this.i = 0;
    }
    sortStep() {
        if (this.i >= this.values.length) {
            this.isDone = true;
            return;
        }
        let jMin = this.i;
        for (let j = this.i + 1; j < this.values.length; j++) {
            /* if this element is less, then it is the new minimum */
            if (this.values[j] < this.values[jMin]) {
                /* found new minimum; remember its index */
                jMin = j;
            }
        }
        if (jMin != this.i) {
            const tmp = this.values[this.i];
            this.values[this.i] = this.values[jMin];
            this.values[jMin] = tmp;
        }
        this.i++;
        this.iterations++;
        setTimeout(() => this.asyncSort(), ITERATION_DELAY);
    }
}

class MergeSorter extends Sorter {
    i: number;
    left: number[];
    right: number[];
    constructor(p5, pos) {
        super(p5, pos);
        this.name = "Merge sort";
    }
    customResetValues() {
        this.i = 0;
    }
    merge(left: number[], right: number[]) {
        const r = [];
        while (left.length && right.length) {
            if (!right.length || left[0] <= right[0]) {
                r.push(left.shift());
            } else {
                r.push(right.shift());
            }
        }
        while (left.length) {
            r.push(left.shift());
        }
        while (right.length) {
            r.push(right.shift());
        }
        console.log(r);
        return r;
    }
    mergeSort(list: number[]) {
        if (list.length <= 1) {
            return list;
        }
        let left: number[] = [];
        let right: number[] = [];
        for (let i = 0; i < list.length; i++) {
            const x = list[i];
            if (i < list.length / 2) {
                left.push(x);
            } else {
                right.push(x);
            }
        }
        left = this.mergeSort(left);
        right = this.mergeSort(right);
        const merged = this.merge(left, right);
        this.values = merged;
        return merged;
    }
    sortStep() {
        this.mergeSort(this.values);
    }
}

console.clear();
const SORTER_HEIGHT = 150;
const NB_VALUES = 100;
const ITERATION_DELAY = 100;
let BAR_WIDTH;
const sketch = (p5: P5) => {
    let sorters: Sorter[];

    let resetSorters = () => {
        // Generate the values
        BAR_WIDTH = p5.width / NB_VALUES;
        const values = new Array(NB_VALUES);
        for (let i = 0; i < values.length; i++) {
            values[i] = Math.floor(p5.random(SORTER_HEIGHT));
        }
        for (const sorter of sorters) {
            sorter.resetValues(values);
        }
        for (const sorter of sorters) {
            sorter.asyncSort();
        }
    };
    p5.setup = () => {
        sorters = [
            new BubbleSorter(p5, 1),
            new SelectionSorter(p5, 2)
            //new MergeSorter(p5, 3)
        ];
        p5.createCanvas(700, SORTER_HEIGHT * sorters.length);

        resetSorters();
    };

    // The sketch draw method
    p5.draw = () => {
        p5.background(10, 10, 10);
        let nbSortersDone = 0;
        for (const sorter of sorters) {
            if (sorter.isDone) {
                nbSortersDone++;
            }
            sorter.draw();
        }
        if (nbSortersDone === sorters.length) {
            resetSorters();
        }
    };
};

new p5(sketch);

              
            
!
999px

Console