Skip to content

Instantly share code, notes, and snippets.

@huahualeetcode
Last active January 4, 2019 04:47
Show Gist options
  • Save huahualeetcode/67f1becf049d3916593fb502b301ff95 to your computer and use it in GitHub Desktop.
Save huahualeetcode/67f1becf049d3916593fb502b301ff95 to your computer and use it in GitHub Desktop.
// Author: Huahua (https://www.youtube.com/user/xxfflower)
// p5 web editor: https://editor.p5js.org
var N = 50;
var K = 100;
var w = 10;
var h = 4;
var s;
var running = true;
function SelectSort() {
this.init = function() {
this.a = [];
this.i = 0;
this.j = 0;
for (var i = 0; i < N; ++i)
this.a.push(floor(random() * K));
}
this.draw = function() {
for (var i = 0; i < N; ++i) {
if (i == this.i) {
fill(255, 0, 0);
} else if (i == this.j) {
fill(0, 0, 255);
} else {
fill(255);
}
rect(i * w, K * h - this.a[i] * h, w, this.a[i] * h);
}
}
this.sort = function() {
// for (var i = 0; i < N; ++i)
// for (var j = i + 1; j < N; ++j)
// if (a[i] > a[j]) swap(a[i], a[j])
if (this.i == N) return;
if (this.a[this.i] > this.a[this.j]) {
var tmp = this.a[this.i];
this.a[this.i] = this.a[this.j];
this.a[this.j] = tmp;
}
if (++this.j == N) {
this.j = ++this.i + 1;
}
}
}
function setup() {
createCanvas(N * w, K * h);
s = new SelectSort();
s.init();
}
function draw() {
background(30);
if (running)
s.sort();
s.draw();
}
function keyPressed() {
if (keyCode === ENTER) {
setup();
} else if (keyCode === 32) {
running = !running;
} else if (keyCode === RIGHT_ARROW) {
running = false;
s.sort();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment