I have several divs
with random numbers on them that I latter arrange on an ascending order using some simple bubble sorting code, I would like to gradually arrange and add style to them instead of them being styled and arranged immediately.
This feels like something so simple yet I'm unable to find a way to sleep
the for loop
or use the setTimeout
function properly... Also extra points if it highlights the two divs
that are being currently compared.
Here's a working example of what I've got so far:
function bubbleSort(input) {
var swapped;
do {
swapped = false;
for (var i=0; i < input.length-1; i++) {
var div1 = $('.divRandom').eq(i);
var div2 = $('.divRandom').eq(i+1);
if (input[i] > input[i+1]) {
var temp = input[i];
input[i] = input[i+1];
input[i+1] = temp;
arrangeDivs(div1, div2);
swapped = true;
}
}
} while (swapped);
}
function arrangeDivs(div1, div2){
div1.before(div2);
div1.removeClass('divUnsorted');
div1.addClass('divSorted');
div2.removeClass('divUnsorted');
div2.addClass('divSorted');
}
$('.bubbleBtn').click(function() {
var divArray = new Array();
divArray = createArray(divArray);
//console.log(divArray);
bubbleSort(divArray);
//console.log(divArray);
});
function createArray(divArray) {
var divLength = $('.divUnsorted').length;
for (var i = 0; i < divLength; i++){
var divNumber = parseInt($('.divUnsorted').eq(i).text());
divArray.push(divNumber)
}
return divArray;
}
$('.addDivBtn').click(function(){
$('.divRandom').removeClass('divSorted');
$('.divRandom').addClass('divUnsorted');
var randomNumber = Math.floor((Math.random() * 1000) + 1);
$('<div/>', {
'class':'divRandom divUnsorted',
'text':randomNumber,
}).appendTo('.addDivRandom');
$('.divRandom').addClass('divUnsorted');
});
.divRandom {
display: inline-block;
text-align: center;
margin: 5px;
padding: 10px;
width: 100px;
font-size: 20px;
}
.addDivRandom {
text-align: center;
margin: auto;
}
.divUnsorted {
border: 2px solid green;
background-color: #9db;
}
.divSorting {
border: 2px solid darkred;
background-color: #db9;
}
.divSorted {
border: 2px solid darkblue;
background-color: #9bd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="addDivRandom">
</div>
<button class="addDivBtn" style="display: block;">Add</button>
<button class="bubbleBtn" style="display: block;">Bubble</button>
See Question&Answers more detail:os