Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

javascript - How to gradually style elements that are being (bubble) sorted?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...