One approach to this could be to change it to add a delay between each swap. The below logic has refactored the bubbleSort method to use an inner IIFE.
This IIFE performs a setTimeout of 0.5 seconds. Each execution it checks to see if an element should be swapped, and swaps them if it should. If the index is not at the end of the loop, it calls the IIFE for the next index to keep evaluating. Once it reaches the end of the loop, if a swap has happened, it calls bubbleSort again to start the process all over.
function bubbleSort(input) {
var swapped = false;
(function swapDivs ( index ){
console.log( index );
setTimeout(function(){
if ( index < input.length - 1 ) {
var $divs = $('.divRandom'),
$div1 = $divs.eq( index ),
$div2 = $divs.eq( index + 1 );
if ( input[ index ] > input[ index + 1 ] ) {
var temp = input[ index ];
input[ index ] = input[ index + 1 ];
input[ index + 1 ] = temp;
arrangeDivs( $div1, $div2 );
swapped = true;
}
swapDivs( index + 1 );
}
else if ( swapped ) {
$('.divRandom.divSorted').toggleClass('divSorted divUnsorted');
bubbleSort( input );
}
}, 500);
})(0);
}
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>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…