Created
November 3, 2017 16:51
-
-
Save levymoreira/a1b3ebeb194aa5647bc1b530961ecb12 to your computer and use it in GitHub Desktop.
MergeSort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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