Javascript merge sort visualisation

前端 未结 2 488
自闭症患者
自闭症患者 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:53

    In order to visualize the sort we need to draw at intervals during the sort. Here I have added a depth variable so that I can control how far the sort goes. Each time draw is called I increment depth so we can see progress.

    var values = [];
    var numLines = 500;
    
    function setup() {
      createCanvas(900, 600);
      colorMode(HSB, height);
      for (i = 0; i < numLines; i++) {
        values[i] = (round(random(height)));
      }
      frameRate(1);
     }
    
    var depth = 1;
    function draw() {
      background(51);
      values = mergeSort(values, depth);
      depth++;
      for (i = 0; i < values.length; i++) {
        let col = color(values[i], height, height);
        stroke(col);
        fill(col);
        var location = map(i, 0, values.length, 0, width);
        rect(location, height - values[i], width/numLines, height);
      } 
      if (depth > 10){
       noLoop();
      }
    }
    
    function mergeSort(a, d) {
      if (a.length <= 1) {
        return a;
      }
      d--;
      if (d < 1){
        return a;
      }
      var mid = Math.round((a.length / 2));
      var left = a.slice(0, mid);
      var right = a.slice(mid);
      return merge(mergeSort(left,d), mergeSort(right, d));
    }
    
    function merge(left, right) {
      sorted = [];
      while (left && left.length > 0 && right && right.length > 0) {
        if (left[0] <= right[0]) {
          sorted.push(left.shift());
        }
        else {
          sorted.push(right.shift());
        }
      }
      return sorted.concat(left, right);
    }

提交回复
热议问题