我已经完成了处理过程中冒泡排序的可视化。我自己的下一步是希望能够通过将颜色更改为红色来查看正在排序的行。我不确定如何解决这个问题,任何见解都会有所帮助。
我尝试在开关算法的中间添加笔划,并将其放入检查值的算法中,但都不起作用。
float[] lines;
int i = 0;
int j = 0;
void setup() {
//fullScreen(P2D);
size(800,500);
//get array of x values
lines = new float[width];
float len = lines.length;
//populate each x value with a random y value
for (int i = 0; i < len; i++) {
lines[i] = random(height);
}
}
void draw() {
background(0);
float len = lines.length;
//do this for the entire array
if (i < len) {
for (j = 0; j < len-i-1; j++) {
float a = lines[j];
float b = lines[j + 1];
if (a > b) {
swap(lines, j, j+1);
}
}
} else {
noLoop();
i++;
}
for (int i = 0; i < len; i++) {
stroke(255);
line(i, height, i, height - lines[i]);
}
}
void swap(float[] arr, int a, int b) {
float temp;
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
这是现在的工作代码,无需将颜色更改为红色,我包含了完整的程序,因此您可以自己尝试一下,看看是否可以帮助更改正在移动并交换为红色的单行。
最佳答案
使用IntList
收集已交换行的索引:
例如
IntList swapped = new IntList();
if (a > b) {
swapped.append(j);
swapped.append(j+1);
swap(lines, j, j+1);
}
如果列表中包含线条的索引,则以不同的颜色绘制线条:
例如
for (int i = 0; i < len; i++) {
if ( swapped.hasValue(i) )
stroke(255, 0, 0);
else
stroke(255);
line(i, height, i, height - lines[i]);
}
函数draw
可能如下所示:
void draw() {
background(0);
IntList swapped = new IntList();
float len = lines.length;
//do this for the entire array
if (i < len) {
for (j = 0; j < len-i-1; j++) {
float a = lines[j];
float b = lines[j + 1];
if (a > b) {
swapped.append(j);
swapped.append(j+1);
swap(lines, j, j+1);
}
}
} else {
noLoop();
i++;
}
for (int i = 0; i < len; i++) {
if ( swapped.hasValue(i) )
stroke(255, 0, 0);
else
stroke(255);
line(i, height, i, height - lines[i]);
}
}
关于java - 如何通过将颜色更改为红色来显示正在排序的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56112833/