JSFiddle - React, Tailwind, and code Playground
by Mert Ener
HTML
<article id="box">
</article>
CSS
body {
height: 400px;
background-color: rgb(30,31,31);
}
#box {
position: relative;
padding:0;
width: 800px;
min-height: 100% !important;
height: auto;
}
#box>div {
box-sizing: border-box;
position: absolute;
display:block;
width: 8px;
background-color: red;
border:1px solid black;
bottom:0;
}
JavaScript
function reset() {
let box = document.getElementById("box");
while (box.firstChild) box.removeChild(box.firstChild);
let left = 0;
let myRands = [];
for (let e=0;e<100;e++) {
let myloop=true;
let node = document.createElement("div");
while (myloop) {
let myRand = Math.floor(Math.random() * (100) + 1)*4;
if (myRands.indexOf(myRand) === -1) {
myRands.push(myRand);
document.getElementById("box").appendChild(node);
node.style.height = myRand+"px";
node.style.left = left+"px";
left+=8;
myloop=false;
}
}
}
let i=1,j=0,minItem=0,tmp,mini,comp,insr;
function bubbleSort () {
mini = document.getElementsByTagName("div")[minItem];
mini.style.backgroundColor = "#00FF00";
comp = document.getElementsByTagName("div")[i];
comp.style.backgroundColor = "#FFFF00";
setTimeout(function() {
if (comp.offsetHeight<mini.offsetHeight) {
mini.style.backgroundColor = "red";
mini = comp;
mini.style.backgroundColor = "#00FF00";
minItem=i;
} else {
comp.style.backgroundColor = "red";
}i++;},1);
setTimeout(function() {
if (i==100) {
insr = document.getElementsByTagName("div")[j];
tmp=insr.offsetHeight;
insr.style.height=mini.offsetHeight+"px";
mini.style.backgroundColor = "red";
insr.style.backgroundColor = "#00FF00";
mini.style.height=tmp+"px";
minItem=j++;
i=++minItem;
}
},1);
if (j==99) {
document.getElementsByTagName("div")[j].style.backgroundColor = "#00FF00";
let r=0;
let finalRed = setInterval(function(){
document.getElementsByTagName("div")[r].style.backgroundColor = "red";
r==100?clearInterval(finalRed):r++;
}, 20);
setTimeout(reset,2000);}
setTimeout(bubbleSort, 1);
}
bubbleSort();
}
reset();