Skip to content

Instantly share code, notes, and snippets.

@levymoreira
Created November 3, 2017 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save levymoreira/a1b3ebeb194aa5647bc1b530961ecb12 to your computer and use it in GitHub Desktop.
Save levymoreira/a1b3ebeb194aa5647bc1b530961ecb12 to your computer and use it in GitHub Desktop.
MergeSort
const _ = require('underscore');
class MergeSort {
sort(arr) {
if(arr.length === 1) {
return arr;
}
const half = Math.floor(arr.length / 2);
const left = arr.slice(0, half);
const right = arr.slice(half, arr.length);
return this.merge(this.sort(left), this.sort(right));
}
merge(left, right) {
let result = [];
while (left.length > 0 || right.length > 0) {
if (left.length > 0 && right.length > 0) {
if (left[0] < right[0]) {
result.push(left.shift());
} else {
result.push(right.shift());
}
} else if (left.length > 0) {
result.push(left.pop())
} else {
result.push(right.pop())
}
}
return result;
}
}
const test = (currentResult, expectedResult) => {
if (!_.isEqual(currentResult, expectedResult)) {
console.log('Error!');
} else {
console.log('Success.');
}
}
var obj = new MergeSort();
test(obj.sort([10,1,3,11]), [1,3,10,11]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment