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

标签 java processing bubble-sort

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

我尝试在开关算法的中间添加笔划,并将其放入检查值的算法中,但都不起作用。

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/

相关文章:

java - 根据键对java对象进行排序

java - 如何将文件传递给阻止上游作业的下游作业?

java - 在带有finally block 的方法中放置return 语句

java - 从 org.apache.cxf.binding.soap.SoapMessage 中提取信息

google-maps - 如何使用 Google map 进行处理?

C 链表冒泡排序逻辑错误

java - 冒泡排序日历

Java Swing - 将矩形拖到 JPanel 上的有效方法?

java - processing.org 中的舍入 float

java - 检查两个非常长的数组是否至少有一个公共(public)元素的最快(运行时)方法?