Skip to content

Instantly share code, notes, and snippets.

@tuscen
Last active December 22, 2015 00:45
Show Gist options
  • Select an option

  • Save tuscen/a2f432be9c46505e6d0c to your computer and use it in GitHub Desktop.

Select an option

Save tuscen/a2f432be9c46505e6d0c to your computer and use it in GitHub Desktop.
Functional merge sort in JS
'use strict';
var mergesort = (function () {
"use strict";
function sort(array) {
if (array.length < 2) {
return array;
}
const length = array.length
, mid = Math.floor(length * 0.5)
, left = array.slice(0, mid)
, right = array.slice(mid, length);
return merge(sort(left), sort(right));
}
function merge(left, right) {
function iter(current, other, acc) {
if (current.length === 0) {
return acc.concat(other);
} else if(other.length === 0) {
return acc.concat(current);
}
const [newCurrent, newOther] = current[0] <= other[0] ?
[current, other] : [other, current];
return iter(newCurrent.slice(1), newOther, acc.concat([newCurrent[0]]));
};
return iter(left, right, []);
}
return {
sort: sort
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment