0

I'm trying to show how selection sort works through D3. Everytime I call my selectionSort though, it waits the appropriate time and then just shows the sorted numbers. I even looked through the console and it seems that the console is just printing out the sort array multiple times instead of traversing though it at each swap.

  function selectionSort(data) {
  for (var i = 0; i < data.length; i++) {
    for (var j = i + 1; j < data.length; j++) {
      if (data[i] > data[j]) {
        var temp = data[i];
        data[i] = data[j];
        data[j] = temp;
        setTimeout(function() {
          update(data);
        }, 3000);
      }
    }
  }
}

var data = [5, 3, 1, 2, 4];

var svg = d3.select("#first").append("svg")
.attr("width", 500)
.attr("height", 500);


update(data);
selectionSort(data);

function update(data) {
  var bar = svg.selectAll(".myText").data(data);

  bar.exit().remove();

  bar.enter()
  .append("text")
  .attr("class", "myText")
  .attr("x", function(d, i) {
    return 20 + i*16;
  })
  .attr("y", 20);

  bar.text(function(d) {
    return d;
  });

}
Kobe M.
  • 40
  • 8
  • I'm still confused as to what you want the outcome to be -- are you saying for the `for` loop you want to see the sorted list everytime its swapped? – aug Sep 02 '16 at 21:05
  • The call to `setTimeout` will queue the call to `update()` to be executed after 3000 ms. After `update()` is queued, the function `setTimeout()` will return immediately and the loop continues. Thus, the array will be ordered before `update()` will be executed for the first time. Note, that this will happen even if the timeout would be set to 0 ms. An in-depth discussion about this can be found in the excellent article [How JavaScript Timers Work](http://ejohn.org/blog/how-javascript-timers-work/) and the following [answer](http://stackoverflow.com/a/4575011/4235784). – altocumulus Sep 02 '16 at 21:05

0 Answers0