Search code examples
javaprocessingbubble-sort

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


I have completed a visualization of bubble sort in processing. My next step for myself is wanting to be able to see which line is being sorted by changing its color to red. Im not sure how to go about this, any insight would be helpful.

I've tried adding the stroke in the middle of the switch algorithm and also putting it in the algorithm that checks the values too, neither worked.

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

This is the working code right now without changing color to red, i included the full program so you can try it yourself and see if you can help with changing the single line that is being moved and swapped to red.


Solution

  • Use IntList to collect the indices of the lines which have been swapped:

    e.g.

    IntList swapped = new IntList();
    
    if (a > b) {
        swapped.append(j);
        swapped.append(j+1);
        swap(lines, j, j+1);
    }
    

    If an index of a line is contained in the list the draw the line in a different color:

    e.g.

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

    The function draw may look like this:

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