JSFiddle - React, Tailwind, and code Playground
by BurpmanJunior
HTML
<div id="render">
</div>
CSS
body{
background-color: #111;
font-family: monospace;
color: #76959b;
text-align: center;
}
div{
display: flex;
justify-content: center;
align-items: flex-end;
}
.sorted span{
background-color: #01C6EA;
}
span{
display: block;
background-color: #7c8384;
width: 5px;
margin-right: 0px;
}
.active{
background-color: #01C6EA;
}
JavaScript
/**
* Linear swap sort
*/
var _s = _s || {};
_s.init = function(n){
console.clear();
this.elem = document.getElementById('render');
this.a = [];
this.sorted = false;
this.currentSort = 0;
for(var i = 0; i < n; i++){
//this.a[i] = 10 + (20 * (i % 3)); // Boolean output
//this.a[i] = i; // Linear output
//this.a[i] = i * Math.random(); // Noisy linear output
this.a[i] = Math.random() * n; // Random
}
this.a = _s.shuffle(_s.a);
_s.render(_s.a);
_s.sort(_s.a);
}
_s.sort = function(a){
var n = 0;
var sortingLoop = function(){
_s.render(a, _s.currentSort);
a = _s.swapCompare(a);
if(a){
setTimeout(sortingLoop, 10);
}else{
_s.elem.className = 'sorted';
_s.elem.getElementsByClassName('active')[0].removeAttribute('class');
console.log('Sorted array\nTotal moves: %d', n);
var e = document.createElement('p');
e.innerHTML = 'Total moves: ' + n;
document.body.appendChild(e);
}
n++;
};
sortingLoop();
}
_s.swapCompare = function(a){
for(var i = 0; i < a.length - 1; i++){
if(a[i] > a[i+1]){
var swapUp = a[i],
swapDown = a[i+1];
a[i] = swapDown;
a[i+1] = swapUp;
_s.currentSort = i;
return a;
}
}
return false;
}
_s.render = function(a, c){
var h = '';
for(var i = 0; i < _s.a.length; i++){
h += '<span '+(c == i ? 'class="active" ' : '')+'style="padding-top: '+_s.a[i]+'px;"></span>';
}
_s.elem.innerHTML = h;
}
_s.shuffle = function(array){
var currentIndex = array.length, temporaryValue, randomIndex;
while(currentIndex !== 0){
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
...