Skip to content

Instantly share code, notes, and snippets.

@unimonkiez
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unimonkiez/61c63d232767a967be71 to your computer and use it in GitHub Desktop.
Save unimonkiez/61c63d232767a967be71 to your computer and use it in GitHub Desktop.
Bubble sort visualization using ES6
<div class="messy-array">
</div>
'use strict';
const numberWidth = 70;
const delayBetweenAnimations = 500;
/**
* bubbleSort method
*/
Array.prototype.bubbleSortGen = function*() {
let swap = function(elms, i1, i2) {
const t = elms[i1];
elms[i1] = elms[i2];
elms[i2] = t;
}
for (let i = 0, len = this.length; i < len; i++) {
for (let j = 0, last = len - i; j < last; j++) {
if (this[j] > this[j + 1]) {
yield j;
swap(this, j, j + 1);
}
}
}
}
Array.prototype.bubbleSort = function() {
// Run generator until end
while (this.bubbleSortGen().next().done === false);
return this;
}
let loopThroughGeneratorWithDelay = function() {
let i = 0;
let runNext = function(generator, fn, delay) {
let next = generator.next();
if (next.done === false) {
fn(next.value);
setTimeout(runNext.apply.bind(runNext, null, arguments), delay);
}
}
runNext.apply(this, arguments);
}
let CALLBACK = function(givenArray) {
let divsArray = new Array(givenArray.length);
let frag = document.createDocumentFragment();
givenArray.forEach((value, index) => {
var div = document.createElement("div");
div.classList.add('num');
div.innerHTML = value;
div.style.width = numberWidth + 'px';
div.style.left = (numberWidth * index) + 'px';
div.style.backgroundColor = "#" + ("000000" + (Math.floor(Math.random() * 0xFFFFFF)).toString(16)).substr(-6);
divsArray[index] = div;
frag.appendChild(div);
});
document.getElementsByClassName('messy-array')[0].appendChild(frag);
// Start sorting
let gen = givenArray.bubbleSortGen();
loopThroughGeneratorWithDelay(givenArray.bubbleSortGen(), function(value) {
const bigElement = divsArray[value];
const smallElement = divsArray[value + 1];
// Swap
divsArray[value] = smallElement;
divsArray[value + 1] = bigElement;
// Change Css accordingly
smallElement.style.left = (numberWidth * value) + 'px';
bigElement.style.left = (numberWidth * (value + 1)) + 'px';
}, delayBetweenAnimations);
}
CALLBACK([17, 190, 4, 33, 18, 61, 68, 77, 62, 60, 43, 1]);
<script src="http://codepen.io/Janaka-Steph/pen/MwVWQr"></script>
.messy-array{
position: relative;
}
.messy-array>.num{
position: absolute;
height: 70px;
transition: left 0.3s ease-in-out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment