Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions src/merge-sort/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
function stitch(left, right) {
const results = [];
while (left.length && right.length) {
if (left[0] < right[0]) {
results.push(left.shift());
} else {
results.push(right.shift());
}
}

while (left.length) {
results.push(left.shift());
}

while (right.length) {
results.push(right.shift());
}

return results;
}

export const mergeSort = (arr) => {
const unsorted = arr;
if (unsorted.length < 2) {
return unsorted;
}

const length = unsorted.length;
const middle = Math.floor(length / 2);
const left = unsorted.slice(0, middle);
const right = unsorted.slice(middle, length);

return stitch(mergeSort(left), mergeSort(right));
};
50 changes: 50 additions & 0 deletions test/merge-sort.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* sorting-js
*
* Copyright © 2018 Neelesh Roy. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/

import { expect } from 'chai';
import { mergeSort } from '../src/merge-sort/index';


describe('Merge Sort', () => {

describe('Merge Sort - function', () => {

it('should return empty array', () => {
const test = [];

const out = mergeSort(test);

expect(out).to.eql([]);
});

it('should sort the elements in ascending order', () => {
const test = [2, 5, 4, 10, 5, 3, 2, 7];

const out = mergeSort(test);

expect(out).to.eql([2, 2, 3, 4, 5, 5, 7, 10]);
});

it('should sort the string elements', () => {
const test = ['ayda', 'xsy', 'aaa', 'awb', 'cdf'];

const out = mergeSort(test);

expect(out).to.eql(['aaa', 'awb', 'ayda', 'cdf', 'xsy']);
});

it('should sort the floats elements', () => {
const test = [1.23, 9.78, 5.34, 3.45, 3.44];

const out = mergeSort(test);

expect(out).to.eql([1.23, 3.44, 3.45, 5.34, 9.78]);
});
});
});