Javascript merge sort visualisation

前端 未结 2 452
自闭症患者
自闭症患者 2021-01-24 08:24

I have managed to get a merge sort working in p5.js to sort different length lines but can not figure out how to actually show them being sorted. I.e show them unsorted and then

2条回答
  •  无人共我
    2021-01-24 08:52

    This answer uses a non-recursive merge sort that keeps a history of the stages of the sort. The entire sort is performed before draw and then draw steps through all the stages so that we can see how the algorithm moves the lines to achieve the sort. The code is adapted from Mike Bostock's Visualizing Algorithms.

    https://bost.ocks.org/mike/algorithms/ https://bl.ocks.org/mbostock/1b5450d525babd28425f

    var values = [];
    var numLines = 500;
    var sortHist = [];
    function setup() {
      createCanvas(900, 600);
      colorMode(HSB, height);
      for (i = 0; i < numLines; i++) {
        values[i] =random(height);
      }
      sortHist = mergeSort(values);
      frameRate(1);
    }
      
    var historyIndex = 0;
    function draw() {
      background(51);
      for (i = 0; i < sortHist[historyIndex].length; i++) {
        let col = color(sortHist[historyIndex][i], height, height);
        stroke(col);
        fill(col);
        var location = map(i, 0, sortHist[historyIndex].length, 0, width);
        rect(location, height - sortHist[historyIndex][i], width/numLines, height);
      } 
      historyIndex++;
      if (historyIndex > sortHist.length -1){
        noLoop();
      }
    }
    
    function mergeSort(array) {
      var arrays = [array.slice()],
      n = array.length,
      array0 = array,
      array1 = new Array(n);
    
      for (var m = 1; m < n; m <<= 1) {
        for (var i = 0; i < n; i += (m << 1)) {
          merge(i, Math.min(i + m, n), Math.min(i + (m << 1), n));
        }
        arrays.push(array1.slice());
        array = array0, array0 = array1, array1 = array;
      }
    
    function merge(left, right, end) {
      for (var i0 = left, i1 = right, j = left; j < end; ++j) {
        array1[j] = array0[i0 < right && (i1 >= end || array0[i0] <=    array0[i1]) ? i0++ : i1++];
       }
     }
     return arrays;
    }  

提交回复
热议问题