如何通过将颜色更改为红色来显示正在排序的行?

How to show which line is being sorted by changing the color to red?

我已经完成了处理过程中冒泡排序的可视化。我自己的下一步是希望能够通过将颜色更改为红色来查看正在对哪一行进行排序。我不确定该怎么做,任何见解都会有所帮助。

我试过在切换算法的中间添加笔划,也尝试将其放入检查值的算法中,但都没有用。

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]);
    }
}