From 8d79125bd46d21c71f4cc9276d16bcd9d5a3a3e4 Mon Sep 17 00:00:00 2001 From: FeschenkoNatalia Date: Fri, 6 Apr 2018 11:43:32 +0300 Subject: [PATCH] Fix merge sort --- lib/sorts/merge-sort/index.js | 30 +++++++++++++++++++++++++ lib/sorts/merge-sort/merge-sort.test.js | 18 +++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 lib/sorts/merge-sort/index.js create mode 100644 lib/sorts/merge-sort/merge-sort.test.js diff --git a/lib/sorts/merge-sort/index.js b/lib/sorts/merge-sort/index.js new file mode 100644 index 0000000..08473ee --- /dev/null +++ b/lib/sorts/merge-sort/index.js @@ -0,0 +1,30 @@ +function merge(left, right) { + const result = []; + while (left.length && right.length) { + if (left[0] <= right[0]) { + result.push(left.shift()); + } else { + result.push(right.shift()); + } + } + while (left.length) { + result.push(left.shift()); + } + + while (right.length) { + result.push(right.shift()); + } + return result; +} + +module.exports = function mergeSort(array) { + if (array.length === 0 || array.length < 2) { + return array; + } + const middle = Math.floor(array.length / 2); + const left = array.slice(0, middle); + const right = array.slice(middle, array.length); + + return merge(mergeSort(left), mergeSort(right)); +}; + diff --git a/lib/sorts/merge-sort/merge-sort.test.js b/lib/sorts/merge-sort/merge-sort.test.js new file mode 100644 index 0000000..19d5e96 --- /dev/null +++ b/lib/sorts/merge-sort/merge-sort.test.js @@ -0,0 +1,18 @@ + +const should = require('should'); +const algo = require('../../index.js'); + +describe('Merge sort', () => { + it('should return empty array when empty array was passed', () => { + const array = algo.mergeSort([]); + should(array).be.eql([]); + }); + it('should return sorted array if sorted array was passed', () => { + const array = algo.mergeSort([0, 1, 2, 3, 5]); + should(array).be.eql([0, 1, 2, 3, 5]); + }); + it('should return sorted array if any not empty array was passed', () => { + const array = algo.mergeSort([9, 11, 2, 31, 7]); + should(array).be.eql([2, 7, 9, 11, 31]); + }); +});