I have managed to get a merge sort working in p5.js to sort different length lines but can not figure out how to actually show them being sorted. I.e show them unsorted and then update their position as they are being sorted. I'm not sure if there is an easy way to do this with the way my code is currently written or if I need to break the sorting function up and re draw it after each stage?
var values = [];
var numLines = 500;
function setup() {
createCanvas(900, 600);
colorMode(HSB, height);
for (i = 0; i < numLines; i++) {
values[i] = (round(random(height)));
}
values = mergeSort(values);
noLoop();
}
function draw() {
background(51);
for (let i = 0; i < values.length; i++) {
let col = color(values[i], height, height);
stroke(col);
fill(col);
var location = map(i, 0, values.length, 0, width);
rect(location, height - values[i], width/numLines, height);
}
}
function mergeSort(a) {
if (a.length <= 1) {
return a;
}
var mid = Math.round((a.length / 2));
var left = a.slice(0, mid);
var right = a.slice(mid);
return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right) {
sorted = [];
while (left && left.length > 0 && right && right.length > 0) {
if (left[0] <= right[0]) {
sorted.push(left.shift());
}
else {
sorted.push(right.shift());
}
}
return sorted.concat(left, right);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.min.js"></script>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…