xxxxxxxxxx
73
const arraySize = 250;
const lineWidth = 3;
const canvasSize = arraySize * lineWidth;
const fps = 60;
let array;
function setup() {
createCanvas(canvasSize, canvasSize);
frameRate(fps);
array = createRandomArray();
quickSort(0, arraySize - 1);
}
function draw() {
background(0);
drawArray();
}
function quickSort(low, high) {
if (low < high) {
let i = partition(low, high);
quickSort(low, i - 1);
quickSort(i + 1, high);
}
}
function partition(low, high) {
let pivot = array[high];
let i = low - 1;
for (let j = low; j < high; j++) {
if (array[j] < pivot) {
i++;
swap(i, j);
}
}
swap(i + 1, high);
return i + 1;
}
function swap(a, b) {
let temp = array[a];
array[a] = array[b];
array[b] = temp;
}
function drawArray() {
strokeWeight(0.5);
stroke(0);
fill(255);
for (var i = 0; i < array.length; i++) {
const lineHeight = array[i] * lineWidth;
rect(i * lineWidth, canvasSize - lineHeight, lineWidth, lineHeight);
}
}
function createRandomArray() {
let numbers = [];
for (var i = 0; i < arraySize; i++) {
numbers[i] = i;
}
let arr = [];
for (i = 0; i < arraySize; i++) {
arr[i] = numbers.splice(getRandomInt(numbers.length), 1)[0];
}
return arr;
}
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}