2016-08-31 4 views
0

Это мой код для симулятора алгоритма сортировки пузырьков. Алгоритм работает и печатает вывод правильно. Но я хочу отложить каждый шаг в течение 2 секунд, а затем отобразить вывод. Это означает, что я хочу отложить каждую итерацию внутреннего цикла для создания пузырьков. Спасибо.Как применить функцию setTimeout для задержки алгоритма bubbleSort?

<!DOCTYPE html> 
<html> 
<head> 

<style> 
input[type=text], select { 
    width: 60px; 
    padding: 12px 20px; 
    margin: 8px 0; 
    display: inline-block; 
    border: 1px solid #ccc; 
    border-radius: 4px; 
    box-sizing: border-box; 
} 

input[type=button] { 
    width: 70px; 
    background-color: #4CAF50; 
    color: white; 
    padding: 14px 20px; 
    margin: 8px 0; 
    border: none; 
    border-radius: 4px; 
    cursor: pointer; 
} 

input[type=button]:hover { 
    background-color: #45a049; 
} 

div { 
    width:500px; 
    border-radius: 5px; 
    background-color: #f2f2f2; 
    padding: 20px; 
    margin:0 auto; 
} 
Canvas{ 
     padding-left: 0; 
    padding-right: 0; 
    margin-left: auto; 
    margin-right: auto; 
    margin-top:10px; 
    display: block; 
    border-radius: 5px; 
    background-color: #f2f2f2; 




} 
#pp{ 
width:300px; 
margin-left:3px;  

} 
#alltext{ 
height:300px; 
width:500px;  

} 


</style> 
</head> 
<body> 

<h3 align="center"style="text-decoration:underline">Algoritham Simulator</h3> 

<div align="center"> 
    <form > 
    <label >Insert Numbers  </label> 
    <input id="pp" type="text" > 


    <input type="button" onClick="myMove()" value="Sort" > 




    </form> 

</div> 

<canvas id="myCanvas" height="10000" width="900"> 
Your browser does not support the HTML5 canvas tag. 
</canvas> 

<script> 
var height1 = 10; 
var height2 = 50; 
var count =0; 
var canvas; 
var ctx; 

function setCanvas(){ 

    canvas = document.getElementById('myCanvas'); 
    ctx = canvas.getContext('2d'); 
     ctx.canvas.height =10000; 
     ctx.canvas.width = 900; 


} 

function draw(cars,j){ 


     height1+=85; 
     height2+=85; 
     count++; 

     var rectSize = 80; 
     var horizontalGap=1; 



     for(var i=0;i<cars.length;i++) { 


      if(i==j || i==j+1){ 
      ctx.beginPath(); 
      ctx.fillStyle="green"; 
      ctx.fillRect((rectSize+horizontalGap),height1,rectSize,rectSize); 

      ctx.closePath(); 
      ctx.fillStyle="white"; 
      }else{ 
      ctx.beginPath(); 
      ctx.fillStyle="black"; 
      ctx.fillRect((rectSize+horizontalGap),height1,rectSize,rectSize); 
      ctx.closePath(); 
      ctx.fillStyle="white"; 
      } 


      var text = cars[i]; 

      ctx.fillText(text, (rectSize+40)+horizontalGap ,height2); 

      horizontalGap+=100; 


     } 



} 


function myMove() { 
    setCanvas(); 
    var yourArray = []; 
    var inputText = document.getElementById("pp").value; 
    yourArray=inputText.split(","); 


    bubbleSort(yourArray); 
} 


function bubbleSort(items) { 
    var length = items.length; 

    for (var i = 0; i < length; i++) { //Number of passes 

    var c=0; 
     for (var j = 0; j < (length - i - 1); j++) { //Notice that j < (length - i) 
     //Compare the adjacent positions 

    if(items[j] > items[j+1]) { 
     //Swap the numbers 
     var tmp = items[j]; //Temporary variable to hold the current number 
     items[j] = items[j+1]; //Replace current number with adjacent number 
     items[j+1] = tmp; //Replace adjacent number with current number 
     }  
     } 

    draw(items,j);  
    } 

} 



</script> 

</body> 
</html> 
+1

Добро пожаловать в Stack Overflow. Вы можете улучшить свой вопрос. Пожалуйста, прочитайте [Минимальный, Полный и Подтверждаемый пример] (http://stackoverflow.com/help/mcve). Когда ваш код показывает вашу точную проблему ни с чем лишним, вы проявляете уважение к тем, кто добровольно помогает вам. Например, что делает '' CSS'', связанным с вашим вопросом? – zhon

+0

Вы можете просто использовать setTimeout для вызова функции draw – fubbe

ответ

0

Вы не можете просто сделать паузу сценарий JS, но вы можете использовать setTimeout() в очереди функцию, которая будет выполняться после заданной задержки. Это означает, что вы можете использовать setTimeout для создания своего рода псевдо-цикла с задержкой для каждой итерации.

Ниже приведена конверсия исходной вложенной функции петли for для работы с setTimeout().

Я не пытался подключить это к существующему draw() коду, который использует холст - чтобы код был коротким, я просто вызываю свой собственный простой draw() для демонстрационных целей, когда вы нажимаете «Выполнить фрагмент кода», - но это должно дать вам общую идею. (Для демонстрационных целей я использовал гораздо более короткую задержку, чем вы просили, но, очевидно, вы можете изменить это.)

function animatedBubbleSort(items, drawCallback) { 
 
    var i = 0; 
 
    var j = 0; 
 
    var length = items.length; 
 
    
 
    (function nextIteration() { 
 
    if (j >= length - i - 1) { 
 
     j = 0; 
 
     i++; 
 
    } 
 
    if (i < length) { 
 
     if (items[j] > items[j+1]) { 
 
     // swap items 
 
     var temp = items[j]; 
 
     items[j] = items[j+1]; 
 
     items[j+1] = temp; 
 
     drawCallback(items, j+1); 
 
     } 
 
     j++; 
 
     setTimeout(nextIteration, 100); 
 
    } else // finished 
 
     drawCallback(items); 
 
    })(); 
 
} 
 

 
var values = [13, 12, 1, 19, 20, 4, 6, 2, 18, 15, 3, 7, 14, 17, 5, 9, 16, 11, 8, 10]; 
 

 
animatedBubbleSort(values, function draw(items, j) { 
 
    document.getElementById("output").innerHTML = items.map(function(v, i) { return i===j ? "<span>" + v + "</span>" : v; }).join(", "); 
 
});
span { color: red; }
<div id="output"></div>