I am trying to create a bubble sort visualization but I ran into a probem on how do to animate in a one-by-one fashion

Viewed 39

Problem:I am trying to create a bubble sort visualization but it automatically sorts the entire thing when the page is reloaded. I am looking for input to make it slower. Here is my code:

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

Your code is very close but there are a couple of issues.

  1. rename your sort method so that it does not collide with p5js sort
  2. In your sort method do not sort the entire array

Here is your code with the two improvements

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>

Related