bubble sort
by Dong Shelton
HTML
<div id="frame"></div>
CSS
#frame {
position: relative;
width: 400px;
height: 250px;
margin: 0 auto;
background-color: gray;
}
.node {
position: relative;
float: left;
width: 10px;
background-color: black;
}
JavaScript
(function() {
var timeout = 200;
var interval = 200;
function nodesGenerator(n) {
var frame = document.getElementById("frame");
for (var i = 0; i < n; i++) {
var node = document.createElement("div");
node.setAttribute("class", "node");
node.style.height = (Math.floor(Math.random() * 250) + 1) + "px";
frame.appendChild(node);
}
}
nodesGenerator(40);
function bubbleSort (arr) {
for(var i = 0, length1 = arr.length; i < length1; i ++){
setTimeout((function (i, length1) {
return function () {
for(var j = 0, length2 = length1 - i; j < length2 - 1; j ++){
var prev = arr[j].style.height.match(/\d+/);
var next = arr[j+1].style.height.match(/\d+/);
if(parseInt(prev) > parseInt(next)){
var temp = arr[j].style.height;
arr[j].style.height = arr[j+1].style.height;
arr[j+1].style.height = temp;
}
}
}
})(i, length1), timeout+=interval);
}
}
bubbleSort(document.getElementsByClassName("node"));
})();