Bubble Sort
Here is a ChelseaJS visualization of the Bubble Sort algorithm.
Bubble sort is a simple sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order.
Time Complexity: O(n2)
Therefore, Its not a good sorting algorithm for large data sets.
Code
elem=document.querySelector(".example-container");
setCanvas(elem);
arr=[];
for(i=0;i<WIDTH/2;i++){
arr.push(random(0,HEIGHT)); //make a random array
}
k=0;
function draw(){
clearCanvas();
for(j=0;j<arr.length-k-1;j++){
if(arr[j]>arr[j+1]){ //check wrong order
[arr[j] , arr[j+1]] = [arr[j+1],arr[j]]; //es6 destructuring to swap adjacents
swap=true;
}
}
for(i=0;i<arr.length;i++){
x=mapRange(i,0,arr.length,0,WIDTH);
new line(x,HEIGHT,x,HEIGHT-arr[i],'#695fe6',2); //drawing the array
}
if(swap){ //stop swapping if no swap occured
k++;
swap=false;
}
requestAnimationFrame(draw);
}
draw();