Sorting Algorithm

Click the link or highlight the code and copy it.  

Then, go to p5js.org and paste the code in the editor. 

Hit the "run" button, watch what happens. 

Make adjustments to the code, the hit the "run" button again. 

Repeat.  :) 

LINK TO WORKING CODE


let values = []; // Array to be sorted

let i = 0;

let j = 0;


function setup() {

  createCanvas(800, 400);

  values = new Array(width);

  for (let i = 0; i < values.length; i++) {

    values[i] = random(height);

  }

  frameRate(10); // Adjust the speed of visualization

}


function draw() {

  background(0);


  // Bubble Sort

  if (i < values.length) {

    for (let j = 0; j < values.length - i - 1; j++) {

      let a = values[j];

      let b = values[j + 1];

      if (a > b) {

        swap(values, j, j + 1);

      }

    }

  } else {

    console.log("Finished");

    noLoop();

  }


  i++;


  // Display bars

  for (let i = 0; i < values.length; i++) {

    if (i == j || i == j + 1) {

      stroke(255, 0, 0);

    } else {

      stroke(255);

    }

    line(i, height, i, height - values[i]);

  }

}


function swap(arr, a, b) {

  let temp = arr[a];

  arr[a] = arr[b];

  arr[b] = temp;

}