JSFiddle - React, Tailwind, and code Playground
by BurpmanJunior
HTML
<div id="render">
</div>
CSS
body{
background-color: #111;
font-family: monospace;
color: #555;
text-align: center;
}
div{
display: flex;
justify-content: center;
align-items: flex-end;
flex-flow: row wrap;
}
.sorted span{
color: #01C6EA;
}
span{
padding: 2px 5px;
}
.active{
background-color: #01C6EA;
color: #111
}
JavaScript
/**
* Linear swap sort (letters)
*/
var _s = _s || {};
_s.init = function(n){
console.clear();
this.elem = document.getElementById('render');
this.a = [];
this.sorted = false;
this.currentSort = 0;
//var string = 'abcdefghijklmnopqrstuvwxyz0123456789\'.,:;"@-/';
var string = 'abcdefghijklmnopqrstuvwxyz0123456789';
var charArray = string.split('');
for(var i = 0; i < n; i++){
//this.a[i] = (i % 3) + 1; // Stepped output
//this.a[i] = i; // Linear output
//this.a[i] = i * Math.floor(Math.random()); // Noisy linear output
//this.a[i] = Math.floor(Math.random() * n); // Random
this.a[i] = charArray[Math.floor(Math.random() * charArray.length)] + charArray[Math.floor(Math.random() * charArray.length)] + charArray[Math.floor(Math.random() * charArray.length)];
}
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"' :...