问题:我正在尝试创建气泡排序可视化,但是当重新加载页面时,它将自动对整个对象进行排序。我正在寻找输入,以使其变慢。这是我的代码:
let a = [];
let i = 0;
let j = 0;
function setup() {
createCanvas(640, 640);
a = new Array(width);
for (let i = 0; i < a.length; i++) {
a[i] = random(height);
}
}
function draw() {
background(0);
for (let i = 0; i < a.length; i++) {
line(i, height, i, height - a[i]);
stroke(255);
}
if (i < a.length) {
sort(a, i, j);
i++;
}
}
function sort(a, i, j) {
for (i = 0; i < a.length; i++) {
for (j = 0; i < a.length + 1; j++) {
if (a[i] < a[j]) {
let f = a[i];
a[i] = a[j];
a[j] = f;
}
}
}
}
您的代码非常接近,但有两个问题。
这是您的代码,有两个改进
let a = [];
let i = 0;
let j = 0;
function setup() {
createCanvas(640, 640);
a = new Array(width);
for (let i = 0; i < a.length; i++) {
a[i] = random(height);
}
// adjust the frame rate to slow things down even more
frameRate(30);
}
function draw() {
background(0);// black background
for (let k = 0; k < a.length; k++) {
line(k, height, k, height - a[k]);
stroke(255);// white bars
}
if (j < a.length){
for (i = 0; i < a.length; i++) {
mySort(a, i, j);
}
j++;
} else {
noLoop();
}
}
function mySort(a, i, j) {
if (a[i] < a[j]) {
let f = a[i];
a[i] = a[j];
a[j] = f;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js"></script>