Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create quicksort.js #1

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions CC_QuickSort/quicksort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
let values;

function setup() {
createCanvas(600, 400);
values = [];
for (let i = 0; i < width; i++) {
values[i] = random(height);
}
quicksort(values, 0, values.length - 1);
noLoop();
}

function quicksort(arr, lo, hi) {
setTimeout(() => {
redraw();
if (lo < hi) {
let mid = partition(arr, lo, hi);
quicksort(arr, lo, mid - 1);
quicksort(arr, mid + 1, hi);
}
}, 10);
}

function partition(arr, low, high) {
let pivot = arr[high];
let i = (low - 1);
for (let j = low; j <= high - 1; j++) {
if (arr[j] <= pivot) {
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, high);
return (i + 1);
}



function draw() {
render();
}



function render() {
background(0);
for (let i = 0; i < values.length; i++) {
stroke(255);
line(i, height, i, height - values[i]);
}
}

function swap(arr, a, b) {
let temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}