Skip to content

Instantly share code, notes, and snippets.

@nielk
Created January 25, 2015 11:19
Show Gist options
  • Select an option

  • Save nielk/86c9780a6a8efc59d577 to your computer and use it in GitHub Desktop.

Select an option

Save nielk/86c9780a6a8efc59d577 to your computer and use it in GitHub Desktop.
merge-sort.algo

/!\ for training purpose, work in progress ...

javascript implementation :

input: even length and fist half et second half sorted (ex: [1,2,4,8,3,5,6,9])

var merge = function(d) {
  var c = new Array(d.length+1).join('0').split('').map(parseFloat);
  var a = d.slice(0, d.length/2);
  var b = d.slice(d.length/2, d.length);
  var i = 0;
  var j = 0;
  
  for(var k = 0; k < d.length; k++) {
    console.log('loop' + a[i] + b[j]);
    if(a[i] < b[j] || j >= d.length/2) {
      c[k] = a[i];
      i++;
    } else if(b[j] < a[i] || i >= d.length/2) {
      c[k] = b[j];
      j++;
    }
  }
  return c;
};

console.log(merge([1,2,4,8,3,5,6,9]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment