Skip to content
This repository has been archived by the owner on Feb 21, 2021. It is now read-only.

Commit

Permalink
Restyle Merge sort in js (#60)
Browse files Browse the repository at this point in the history
* Merge sort in js

* Added test case of merge sort

* Restyled by clang-format

* Restyled by prettier

Co-authored-by: kheenvraj <[email protected]>
Co-authored-by: Restyled.io <[email protected]>
  • Loading branch information
3 people authored Oct 23, 2020
1 parent 3d0522c commit f9a5b9c
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
35 changes: 35 additions & 0 deletions Sorting/merge_sort/merge_sort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* @param {Array} arr Input array.
* @return {Array} Sorted array.
* @description Merge sort algorithm in JS.
*/

module.exports = {
mergeSort: (arr) => {
var len = arr.length;
if (len < 2) return arr;
var mid = Math.floor(len / 2),
left = arr.slice(0, mid),
right = arr.slice(mid);
// send left and right to the mergeSort to broke it down into pieces
// then merge those
return merge(mergeSort(left), mergeSort(right));
},
};

function merge(left, right) {
var result = [],
lLen = left.length,
rLen = right.length,
l = 0,
r = 0;
while (l < lLen && r < rLen) {
if (left[l] < right[r]) {
result.push(left[l++]);
} else {
result.push(right[r++]);
}
}
// remaining part needs to be addred to the result
return result.concat(left.slice(l)).concat(right.slice(r));
}
6 changes: 6 additions & 0 deletions Sorting/merge_sort/merge_sort.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Test case of merge sort function.
const merge_sort_test = require("./merge_sort.js");

const input = [5345, 55, 3423, 5346, 33];
const sorted = merge_sort_test.mergeSort(input);
console.log("Merge sort", sorted);

0 comments on commit f9a5b9c

Please sign in to comment.