Skip to content

Instantly share code, notes, and snippets.

@Wikunia
Created April 4, 2019 21:22
Show Gist options
  • Save Wikunia/c43ab226c0356907e822749492543df3 to your computer and use it in GitHub Desktop.
Save Wikunia/c43ab226c0356907e822749492543df3 to your computer and use it in GitHub Desktop.
Quicksort CodingTrain sketch
let values = [];
let w = 10;
let states = [];
function setup() {
createCanvas(1850, 1000);
values = new Array(floor(width / w));
for (let i = 0; i < values.length; i++) {
values[i] = random(height);
states[i] = -1;
}
quickSort(values, 0, values.length - 1);
}
async function quickSort(arr, start, end) {
if (start >= end) {
return;
}
let index = await partition(arr, start, end);
states[index] = -1;
await Promise.all([
quickSort(arr, start, index - 1),
quickSort(arr, index + 1, end)
]);
}
async function partition(arr, start, end) {
for (let i = start; i < end; i++) {
states[i] = 1;
}
let pivotValue = arr[end];
let pivotIndex = start;
states[pivotIndex] = 0;
for (let i = start; i < end; i++) {
if (arr[i] < pivotValue) {
await swap(arr, i, pivotIndex);
states[pivotIndex] = -1;
pivotIndex++;
states[pivotIndex] = 0;
}
}
await swap(arr, pivotIndex, end);
for (let i = start; i < end; i++) {
if (i != pivotIndex) {
states[i] = -1;
}
}
return pivotIndex;
}
function drawComparisonLine(start_idx, end_idx) {
if (start_idx != -1) {
stroke(255, 178, 0);
strokeWeight(4);
line(end_idx * w, height - values[end_idx], start_idx * w, height - values[end_idx]);
start_idx = -1;
}
return start_idx;
}
function draw() {
background(0);
let start_idx = -1;
for (let i = 0; i < values.length; i++) {
if(states[i] == 0) {
start_idx = drawComparisonLine(start_idx, i);
fill('#E0777D');
} else if (states[i] == 1) {
fill('#D6FFB7');
if (start_idx == -1) {
start_idx = i;
}
} else {
start_idx = drawComparisonLine(start_idx, i);
fill(255);
}
noStroke()
rect(i * w, height - values[i], w, values[i]);
}
}
async function swap(arr, a, b) {
await sleep(75);
let temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment